#!/usr/bin/env python3
"""Run a command and export its wall time and child CPU time as one OTLP span."""
import argparse
import fcntl
import json
import os
import re
import resource
import secrets
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path


def attribute(key, value):
    if isinstance(value, int):
        field = {"intValue": str(value)}
    elif isinstance(value, float):
        field = {"doubleValue": value}
    else:
        field = {"stringValue": value}
    return {"key": key, "value": field}


def export(span, output, endpoint):
    batch = {"resourceSpans": [{
        "resource": {"attributes": [
            attribute("service.name", "orca-tools"),
            attribute("host.name", socket.gethostname()),
        ]},
        "scopeSpans": [{"scope": {"name": "codeperf.trace-tool"}, "spans": [span]}],
    }]}
    data = json.dumps(batch, separators=(",", ":")).encode()
    spool = os.environ.get("CODEPERF_SPOOL_DIR")
    if spool:
        try:
            target = Path(spool) / f"codeperf-{span['traceId']}-{span['spanId']}.json"
            with tempfile.NamedTemporaryFile(dir=spool, prefix=".codeperf-pending-", delete=False) as pending:
                pending.write(data)
            os.replace(pending.name, target)
        except OSError as exc:
            print(f"trace-tool: buffer write failed: {exc}", file=sys.stderr)
    if output:
        try:
            fd = os.open(output, os.O_APPEND | os.O_CREAT | os.O_WRONLY, 0o600)
            with os.fdopen(fd, "ab") as stream:
                fcntl.flock(stream, fcntl.LOCK_EX)
                stream.write(data + b"\n")
                stream.flush()
        except OSError as exc:
            print(f"trace-tool: file export failed: {exc}", file=sys.stderr)
    if endpoint:
        try:
            request = urllib.request.Request(endpoint, data=data,
                                             headers={"Content-Type": "application/json"})
            with urllib.request.urlopen(request, timeout=2) as response:
                result = json.load(response)
            rejected = result.get("partialSuccess", {})
            if int(rejected.get("rejectedSpans", 0)) or rejected.get("errorMessage"):
                print(f"trace-tool: partial export: {rejected}", file=sys.stderr)
        except (OSError, ValueError, urllib.error.URLError) as exc:
            print(f"trace-tool: HTTP export failed: {exc}", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--workspace", default=os.environ.get("CODEPERF_WORKSPACE") or Path.cwd().name)
    parser.add_argument("--agent", default=os.environ.get("CODEPERF_AGENT", "operator"))
    parser.add_argument("--parent", default=os.environ.get("TRACEPARENT"), help="W3C traceparent")
    parser.add_argument("--root-id", help="Trace ID for a new root (32 lowercase hex digits)")
    parser.add_argument("--name", required=True, help="Short operation label shown in Jaeger")
    parser.add_argument("--file", default=os.environ.get("CODEPERF_TRACE_FILE"), help="Append OTLP JSONL")
    parser.add_argument("command", nargs=argparse.REMAINDER, help="-- PROGRAM [ARG ...]")
    args = parser.parse_args()
    command = args.command[1:] if args.command[:1] == ["--"] else args.command
    if not command:
        parser.error("supply a command after --")

    if args.root_id and (args.parent or not re.fullmatch(r"[0-9a-f]{32}", args.root_id)
                         or int(args.root_id, 16) == 0):
        parser.error("--root-id requires a nonzero trace ID and no parent")
    trace_id = args.root_id or secrets.token_hex(16)
    span_id = secrets.token_hex(8)
    span = {"spanId": span_id, "name": args.name, "kind": 1}
    flags = "01"
    if args.parent:
        match = re.fullmatch(r"00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})", args.parent)
        if not match or not int(match[1], 16) or not int(match[2], 16):
            parser.error("invalid version 00 traceparent")
        trace_id, span["parentSpanId"], flags = match.groups()
    span["traceId"] = trace_id
    context = f"00-{trace_id}-{span_id}-{flags}"
    run = os.environ.get("CODEPERF_RUN") or trace_id
    env = dict(os.environ, TRACEPARENT=context, CODEPERF_WORKSPACE=args.workspace,
               CODEPERF_AGENT=args.agent, CODEPERF_RUN=run)
    if args.file:
        env["CODEPERF_TRACE_FILE"] = os.path.abspath(args.file)
    attributes = [attribute("codeperf.run", run), attribute("workspace.name", args.workspace),
                  attribute("gen_ai.agent.name", args.agent),
                  attribute("process.executable.name", os.path.basename(command[0]))]
    if os.environ.get("CODEPERF_PROFILE_HOST"):
        attributes.append(attribute("codeperf.profile.host", os.environ["CODEPERF_PROFILE_HOST"]))
    if os.environ.get("CODEPERF_WORKTREE_ID"):
        attributes.append(attribute("codeperf.worktree.id", os.environ["CODEPERF_WORKTREE_ID"]))
    span["startTimeUnixNano"] = str(time.time_ns())
    start = time.monotonic_ns()
    try:
        child = subprocess.Popen(command, env=env)
    except OSError as exc:
        print(f"trace-tool: {exc}", file=sys.stderr)
        status = 127 if isinstance(exc, FileNotFoundError) else 126
    else:
        attributes.append(attribute("process.pid", child.pid))
        print(f"trace-tool: {args.name} pid={child.pid} traceparent={context}", file=sys.stderr, flush=True)
        for sig in (signal.SIGTERM, signal.SIGHUP):
            signal.signal(sig, lambda signum, frame: child.send_signal(signum))
        while True:
            try:
                status = child.wait()
                break
            except KeyboardInterrupt:
                child.send_signal(signal.SIGINT)
        if status < 0:
            status = 128 - status
    span["endTimeUnixNano"] = str(int(span["startTimeUnixNano"]) + time.monotonic_ns() - start)
    usage = resource.getrusage(resource.RUSAGE_CHILDREN)
    attributes.extend([attribute("process.exit.code", status),
                       attribute("codeperf.cpu.user_s", usage.ru_utime),
                       attribute("codeperf.cpu.system_s", usage.ru_stime)])
    span["attributes"] = attributes
    if status:
        span["status"] = {"code": 2, "message": f"exit {status}"}
    if int(flags, 16) & 1:
        export(span, args.file, os.environ.get("CODEPERF_TRACE_ENDPOINT", "http://127.0.0.1:4318/v1/traces"))
    return status


if __name__ == "__main__":
    sys.exit(main())
