from __future__ import annotations

import json
from pathlib import Path

from adw_modules.tracer import Tracer


def test_attempt_usage_json_preserves_estimated_usage_and_typed_failure(tmp_path: Path) -> None:
    tracer = Tracer(tmp_path / "trace.db", tmp_path / "events.jsonl")
    tracer.session_start("run-1", "test")
    attempt_id = tracer.agent_attempt_start(
        "run-1",
        "phase-1",
        "builder",
        "session-1",
        "pi -p",
        host="host-a",
        account="acct",
        provider="gpt",
        model="gpt/sol-web-pro",
    )

    tracer.agent_attempt_finish(
        attempt_id,
        returncode=7,
        signal=None,
        timed_out=False,
        stderr_path=str(tmp_path / "stderr.log"),
        tokens=120,
        usage={
            "total_tokens": 120,
            "usage_estimated": True,
            "billing_status": "unavailable",
            "max_tokens": 16000,
        },
        error="pi provider failure [capped]: daily limit reached",
        timeout_kind=None,
        provider_failure={
            "kind": "capped",
            "detail": "daily limit reached",
            "retry_after_seconds": 900,
            "resume_at": "2026-08-11T09:00:00Z",
        },
    )

    stored = tracer.conn.execute(
        "SELECT usage_json,error FROM agent_attempts WHERE attempt_id=?",
        (attempt_id,),
    ).fetchone()
    usage = json.loads(stored[0])
    assert usage["usage_estimated"] is True
    assert usage["billing_status"] == "unavailable"
    assert usage["max_tokens"] == 16000
    assert usage["provider_failure"]["kind"] == "capped"
    assert usage["provider_failure"]["resume_at"] == "2026-08-11T09:00:00Z"
    assert stored[1] == "pi provider failure [capped]: daily limit reached"


def test_attempt_finish_keeps_typed_failure_when_no_usage_exists(tmp_path: Path) -> None:
    tracer = Tracer(tmp_path / "trace.db", tmp_path / "events.jsonl")
    tracer.session_start("run-1", "test")
    attempt_id = tracer.agent_attempt_start(
        "run-1",
        "phase-1",
        "builder",
        "session-1",
        "pi -p",
        host="host-a",
        account=None,
        provider=None,
        model="openai-codex/gpt-5.6-terra",
    )

    tracer.agent_attempt_finish(
        attempt_id,
        returncode=None,
        signal=15,
        timed_out=False,
        stderr_path=str(tmp_path / "stderr.log"),
        tokens=None,
        usage=None,
        error="cancelled",
        timeout_kind=None,
        provider_failure={"kind": "cancelled", "detail": "cancelled"},
    )

    row = tracer.conn.execute(
        "SELECT usage_json FROM agent_attempts WHERE attempt_id=?",
        (attempt_id,),
    ).fetchone()
    assert json.loads(row[0])["provider_failure"] == {"kind": "cancelled", "detail": "cancelled"}
