"""Result-first agent harness.

Measures whether an agent actually solves a task, how long it takes, and what
it costs. Routing is fitted on training tasks only and evaluated on held-out
tasks. No self-reported progress is accepted as a verified result.

The harness works with any Python callable. An optional OpenAI-compatible
adapter is included for real LLM agents (local or remote, user-supplied).
"""

from __future__ import annotations

import argparse
import json
import math
import os
import subprocess
import time
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Sequence

HARNESS_SCHEMA = "sintropa.agent-harness.v1"


@dataclass(frozen=True)
class Agent:
    name: str
    fn: Callable[[Any], Any]


@dataclass(frozen=True)
class Task:
    task_id: str
    payload: Any


@dataclass
class Attempt:
    agent: str
    task_id: str
    output: Any
    score: float
    latency_s: float
    energy_j: float | None
    energy_estimated: bool
    power_source: str | None
    error: str | None = None
    usage: dict[str, Any] | None = None

    def as_dict(self, include_output: bool = False) -> dict[str, Any]:
        data = {
            "agent": self.agent,
            "task_id": self.task_id,
            "score": self.score,
            "latency_s": round(self.latency_s, 6),
            "energy_j": self.energy_j,
            "energy_estimated": self.energy_estimated,
            "power_source": self.power_source,
            "error": self.error,
            "usage": self.usage,
        }
        if include_output:
            data["output"] = self.output
        return data


@dataclass
class Episode:
    task_id: str
    strategy: str
    attempts: list[Attempt]
    best_score: float
    best_output: Any
    total_latency_s: float
    total_energy_j: float | None
    success: bool


@dataclass
class AgentProfile:
    name: str
    attempts: int
    mean_score: float
    success_rate: float
    mean_latency_s: float
    mean_energy_j: float | None
    yield_per_s: float
    yield_per_j: float | None

    def as_dict(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "attempts": self.attempts,
            "mean_score": self.mean_score,
            "success_rate": self.success_rate,
            "mean_latency_s": self.mean_latency_s,
            "mean_energy_j": self.mean_energy_j,
            "yield_per_s": self.yield_per_s,
            "yield_per_j": self.yield_per_j,
        }


def probe_power_w() -> tuple[float | None, str]:
    """Best-effort instantaneous GPU power sample; absence is explicit."""
    try:
        proc = subprocess.run(
            ["nvidia-smi", "--query-gpu=power.draw", "--format=csv,noheader,nounits"],
            capture_output=True,
            text=True,
            timeout=1.0,
            check=False,
        )
        if proc.returncode == 0 and proc.stdout.strip():
            value = float(proc.stdout.strip().splitlines()[0].strip())
            if math.isfinite(value) and value > 0:
                return value, "nvidia-smi-instantaneous"
    except Exception:
        pass
    return None, "unavailable"


def _score(value: Any) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError("evaluator must return a numeric score")
    result = float(value)
    if not math.isfinite(result) or result < 0:
        raise ValueError("evaluator score must be finite and non-negative")
    return result


class ResultHarness:
    def __init__(
        self,
        evaluator: Callable[[Any, Any], float],
        *,
        success_threshold: float = 1.0,
        latency_budget_s: float | None = None,
        energy_budget_j: float | None = None,
        power_sampler: Callable[[], tuple[float | None, str]] | None = None,
    ) -> None:
        self.evaluator = evaluator
        self.success_threshold = float(success_threshold)
        self.latency_budget_s = latency_budget_s
        self.energy_budget_j = energy_budget_j
        self.power_sampler = power_sampler
        if energy_budget_j is not None and power_sampler is None:
            raise ValueError("an energy budget requires an explicit power sampler")

    def measure(self, agent: Agent, task: Task) -> Attempt:
        before_power = self.power_sampler() if self.power_sampler else (None, "not-sampled")
        start = time.perf_counter_ns()
        output = None
        error = None
        try:
            output = agent.fn(task.payload)
        except Exception as exc:  # an agent failure is data, not a harness crash
            error = f"{type(exc).__name__}: {exc}"
        latency = max(1e-9, (time.perf_counter_ns() - start) * 1e-9)
        after_power = self.power_sampler() if self.power_sampler else (None, "not-sampled")

        score = 0.0 if error else _score(self.evaluator(output, task.payload))
        samples = [sample for sample in (before_power, after_power) if sample[0] is not None]
        watts = [sample[0] for sample in samples]
        energy = (sum(watts) / len(watts)) * latency if watts else None
        source = "+".join(dict.fromkeys(sample[1] for sample in samples)) if samples else after_power[1]
        usage = getattr(agent.fn, "last_usage", None)
        return Attempt(
            agent=agent.name,
            task_id=task.task_id,
            output=output,
            score=score,
            latency_s=latency,
            energy_j=energy,
            energy_estimated=energy is not None,
            power_source=source,
            error=error,
            usage=usage,
        )

    def run_episode(self, agents: Sequence[Agent], task: Task, strategy: str) -> Episode:
        if self.energy_budget_j is not None and self.power_sampler()[0] is None:
            raise RuntimeError("energy budget requested but no power sample is available")
        attempts: list[Attempt] = []
        best_score = 0.0
        best_output = None
        total_latency = 0.0
        total_energy = 0.0
        energy_seen = False

        for agent in agents:
            if self.latency_budget_s is not None and total_latency >= self.latency_budget_s:
                break
            if self.energy_budget_j is not None and energy_seen and total_energy >= self.energy_budget_j:
                break
            attempt = self.measure(agent, task)
            attempts.append(attempt)
            total_latency += attempt.latency_s
            if attempt.energy_j is not None:
                total_energy += attempt.energy_j
                energy_seen = True
            if attempt.score > best_score or best_output is None:
                best_score = attempt.score
                best_output = attempt.output
            if best_score >= self.success_threshold:
                break

        return Episode(
            task_id=task.task_id,
            strategy=strategy,
            attempts=attempts,
            best_score=best_score,
            best_output=best_output,
            total_latency_s=total_latency,
            total_energy_j=total_energy if energy_seen else None,
            success=best_score >= self.success_threshold,
        )

    def fit(self, agents: Sequence[Agent], train_tasks: Sequence[Task]) -> list[AgentProfile]:
        if not train_tasks:
            raise ValueError("fit requires at least one training task")
        profiles: list[AgentProfile] = []
        for agent in agents:
            attempts = [self.measure(agent, task) for task in train_tasks]
            mean_score = sum(a.score for a in attempts) / len(attempts)
            success_rate = sum(a.score >= self.success_threshold for a in attempts) / len(attempts)
            mean_latency = sum(a.latency_s for a in attempts) / len(attempts)
            energies = [a.energy_j for a in attempts if a.energy_j is not None]
            mean_energy = sum(energies) / len(energies) if energies else None
            profiles.append(
                AgentProfile(
                    name=agent.name,
                    attempts=len(attempts),
                    mean_score=mean_score,
                    success_rate=success_rate,
                    mean_latency_s=mean_latency,
                    mean_energy_j=mean_energy,
                    yield_per_s=mean_score / mean_latency if mean_latency else 0.0,
                    yield_per_j=(mean_score / mean_energy) if mean_energy else None,
                )
            )
        return profiles

    @staticmethod
    def routed_order(agents: Sequence[Agent], profiles: Sequence[AgentProfile], cost_metric: str) -> list[Agent]:
        by_name = {agent.name: agent for agent in agents}
        available = [p for p in profiles if p.name in by_name]
        if cost_metric == "energy_j" and all(p.yield_per_j is not None for p in available):
            ordered = sorted(available, key=lambda p: (-(p.yield_per_j or 0.0), p.name))
        else:
            ordered = sorted(available, key=lambda p: (-p.yield_per_s, p.name))
        names = [p.name for p in ordered]
        names.extend(agent.name for agent in agents if agent.name not in names)
        return [by_name[name] for name in names]

    @staticmethod
    def summarize(episodes: Sequence[Episode], threshold: float) -> dict[str, Any]:
        if not episodes:
            raise ValueError("at least one episode is required")
        total_score = sum(e.best_score for e in episodes)
        total_latency = sum(e.total_latency_s for e in episodes)
        energies = [e.total_energy_j for e in episodes if e.total_energy_j is not None]
        total_energy = sum(energies) if len(energies) == len(episodes) else None
        attempts = sum(len(e.attempts) for e in episodes)
        return {
            "tasks": len(episodes),
            "total_score": total_score,
            "mean_score": total_score / len(episodes),
            "successes": sum(e.success for e in episodes),
            "success_rate": sum(e.success for e in episodes) / len(episodes),
            "total_latency_s": total_latency,
            "total_energy_j": total_energy,
            "attempts": attempts,
            "score_per_s": total_score / total_latency if total_latency else 0.0,
            "score_per_j": (total_score / total_energy) if total_energy else None,
        }

    def evaluate(
        self,
        agents: Sequence[Agent],
        test_tasks: Sequence[Task],
        profiles: Sequence[AgentProfile],
        *,
        cost_metric: str = "latency_s",
    ) -> dict[str, Any]:
        if not test_tasks:
            raise ValueError("evaluate requires at least one test task")
        routed_agents = self.routed_order(agents, profiles, cost_metric)
        baseline_episodes = [self.run_episode(agents, task, "fixed_order") for task in test_tasks]
        routed_episodes = [self.run_episode(routed_agents, task, "yield_routed") for task in test_tasks]
        baseline = self.summarize(baseline_episodes, self.success_threshold)
        routed = self.summarize(routed_episodes, self.success_threshold)
        return {
            "schema": HARNESS_SCHEMA,
            "success_threshold": self.success_threshold,
            "cost_metric_requested": cost_metric,
            "routing_fitted_on": "training_tasks_only",
            "agent_order_fixed": [a.name for a in agents],
            "agent_order_routed": [a.name for a in routed_agents],
            "profiles": [p.as_dict() for p in profiles],
            "baseline_fixed_order": baseline,
            "routed_yield": routed,
            "comparison": {
                "delta_total_score": routed["total_score"] - baseline["total_score"],
                "delta_latency_s": routed["total_latency_s"] - baseline["total_latency_s"],
                "delta_attempts": routed["attempts"] - baseline["attempts"],
                "same_total_score": routed["total_score"] == baseline["total_score"],
                "routed_has_lower_latency": routed["total_latency_s"] < baseline["total_latency_s"],
                "routed_has_fewer_attempts": routed["attempts"] < baseline["attempts"],
            },
            "notes": [
                "Scores are produced by the supplied evaluator, never by agent self-report.",
                "Routing order is fitted on training tasks only; test tasks are held out.",
                "Equal or different scores are reported without claiming universal improvement.",
                "Energy, when present, is an estimate from instantaneous power samples, not a direct energy measurement.",
            ],
        }


class OpenAICompatibleAgent:
    """Optional real LLM adapter. No network call is made until invoked."""

    def __init__(
        self,
        *,
        model: str,
        base_url: str,
        api_key_env: str = "OPENAI_API_KEY",
        system_prompt: str = "Answer concisely and only with the requested result.",
        max_tokens: int = 128,
        timeout_s: float = 60.0,
    ) -> None:
        self.model = model
        self.base_url = base_url.rstrip("/")
        self.api_key_env = api_key_env
        self.system_prompt = system_prompt
        self.max_tokens = max_tokens
        self.timeout_s = timeout_s
        self.last_usage: dict[str, Any] | None = None

    def __call__(self, payload: Any) -> str:
        key = os.environ.get(self.api_key_env, "")
        is_local = self.base_url.startswith(("http://127.0.0.1", "http://localhost"))
        if not key and not is_local:
            raise ValueError(f"missing API key in environment variable {self.api_key_env}")
        prompt = payload if isinstance(payload, str) else payload.get("prompt", json.dumps(payload))
        url = self.base_url if self.base_url.endswith("/chat/completions") else self.base_url + "/chat/completions"
        body = json.dumps({
            "model": self.model,
            "messages": [
                {"role": "system", "content": self.system_prompt},
                {"role": "user", "content": prompt},
            ],
            "temperature": 0,
            "max_tokens": self.max_tokens,
        }).encode("utf-8")
        headers = {"Content-Type": "application/json"}
        if key:
            headers["Authorization"] = f"Bearer {key}"
        request = urllib.request.Request(url, data=body, headers=headers, method="POST")
        with urllib.request.urlopen(request, timeout=self.timeout_s) as response:
            data = json.loads(response.read().decode("utf-8"))
        self.last_usage = data.get("usage")
        return data["choices"][0]["message"]["content"]


def _demo_report() -> dict[str, Any]:
    """Deterministic function demo, not an LLM benchmark."""
    def fast(task):
        time.sleep(0.001)
        return task["expected"]

    def slow(task):
        time.sleep(0.012)
        return task["expected"]

    def sometimes_wrong(task):
        time.sleep(0.001)
        return task["expected"] if task["a"] % 3 else task["expected"] + 1

    def wrong(task):
        time.sleep(0.001)
        return task["expected"] + 999

    agents = [
        Agent("wrong-first", wrong),
        Agent("accurate-but-slow", slow),
        Agent("sometimes-wrong", sometimes_wrong),
        Agent("accurate-fast", fast),
    ]
    train = [Task(f"train-{i}", {"a": i, "b": i + 1, "expected": i * (i + 1)}) for i in range(1, 9)]
    test = [Task(f"test-{i}", {"a": i, "b": i + 2, "expected": i * (i + 2)}) for i in range(9, 17)]
    harness = ResultHarness(lambda output, task: float(output == task["expected"]))
    profiles = harness.fit(agents, train)
    report = harness.evaluate(agents, test, profiles)
    report.update({
        "benchmark_type": "deterministic_local_function_demo",
        "llm_benchmark": False,
        "evaluator": "exact_numeric_equality",
        "train_tasks": len(train),
        "test_tasks": len(test),
        "energy_measurement": "not_performed",
    })
    return report


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--demo", action="store_true", help="run the deterministic local function demo")
    parser.add_argument("--out", type=Path, help="write the JSON report to this path")
    args = parser.parse_args()
    if not args.demo:
        parser.error("use --demo for the local deterministic run, or import ResultHarness in your code")
    report = _demo_report()
    text = json.dumps(report, indent=2, ensure_ascii=False)
    print(text)
    if args.out:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        args.out.write_text(text + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
