from __future__ import annotations

import json

import pytest
from solders.keypair import Keypair
from solders.signature import Signature

from wzrd import PickResult
from wzrd.agent import AgentChallenge, AgentSession, WZRDAgent, agent_auth_message, load_keypair
from wzrd.client import WZRDError


def test_load_keypair_from_json_path(tmp_path):
    keypair = Keypair()
    keypair_path = tmp_path / "id.json"
    keypair_path.write_text(json.dumps(list(bytes(keypair))), encoding="utf-8")

    loaded = load_keypair(keypair_path)

    assert str(loaded.pubkey()) == str(keypair.pubkey())


def test_authenticate_signs_expected_message(monkeypatch):
    agent = WZRDAgent()
    keypair = Keypair()
    captured: dict[str, str] = {}

    def fake_challenge():
        return AgentChallenge(
            nonce="nonce-123",
            message_format="unused",
            expires_in_secs=300,
        )

    def fake_verify(*, pubkey: str, nonce: str, signature: str) -> AgentSession:
        captured["pubkey"] = pubkey
        captured["nonce"] = nonce
        captured["signature"] = signature
        return AgentSession(token="session-token", pubkey=pubkey, expires_at="later")

    monkeypatch.setattr(agent, "challenge", fake_challenge)
    monkeypatch.setattr(agent, "verify", fake_verify)

    session = agent.authenticate(keypair)

    assert session.token == "session-token"
    assert str(keypair.pubkey()) == captured["pubkey"]
    assert captured["nonce"] == "nonce-123"
    assert Signature.from_string(captured["signature"]).verify(
        keypair.pubkey(), agent_auth_message(captured["pubkey"], captured["nonce"]).encode("utf-8")
    )


def test_status_requires_session_token():
    agent = WZRDAgent()

    with pytest.raises(WZRDError, match="authenticate"):
        agent.status()


def test_report_pick_uses_signal_model_and_embeds_wzrd_metadata(monkeypatch):
    agent = WZRDAgent(token="session-token")
    captured: dict[str, object] = {}

    def fake_authorized_json(path, *, method="GET", payload=None, token=None):
        captured["path"] = path
        captured["method"] = method
        captured["payload"] = payload
        captured["token"] = token
        return {"contribution_id": 7}

    monkeypatch.setattr(agent, "_authorized_json", fake_authorized_json)

    choice = PickResult(
        model="openrouter/qwen/qwen3.5-35b-a3b",
        signal_model="Qwen/Qwen3.5-35B-A3B",
        task="code",
        policy="strict",
        score=0.72,
        raw_score=0.61,
        trend="accelerating",
        confidence="normal",
        action="candidate",
        platform="github",
        reason="strict feed signal from github",
    )

    result = agent.report_pick(choice, quality_score=0.9, latency_ms=800)

    assert result == {"contribution_id": 7}
    assert captured["path"] == "/v1/agent/report"
    assert captured["method"] == "POST"
    assert captured["token"] is None
    payload = captured["payload"]
    assert isinstance(payload, dict)
    assert payload["model_id"] == "Qwen/Qwen3.5-35B-A3B"
    assert payload["task_type"] == "code"
    assert payload["quality_score"] == 0.9
    assert payload["latency_ms"] == 800
    assert payload["metadata"]["wzrd"]["policy"] == "strict"
    assert payload["metadata"]["wzrd"]["reason"] == "strict feed signal from github"
