from __future__ import annotations

from dataclasses import dataclass

from solders.keypair import Keypair

from wzrd.client import PickResult
from wzrd.loop import run_loop


@dataclass
class _FakeSession:
    token: str = "session-token"


class _FakeAgent:
    def __init__(self) -> None:
        self.auth_calls = 0
        self.claim_calls = 0
        self.report_calls = 0

    def authenticate(self, keypair):
        self.auth_calls += 1
        return _FakeSession()

    def earned(self):
        return {
            "pending_ccm": 0,
            "total_earned_ccm": 0,
            "pipeline": {},
        }

    def status(self):
        return {"solana": {"sol_lamports": 1_000_000_000}}

    def infer(self, model, *, task_type=None, pick_id=None):
        return {}

    def report_pick(self, choice, **kwargs):
        self.report_calls += 1
        return {"pending_ccm": 0}

    def claim_status(self):
        return {"claimable_ccm": 0, "relay_ready": True}

    def claim(self):
        self.claim_calls += 1
        return {"status": "already_claimed"}

    def invalidate_session(self):
        return None

    def health_check(self):
        return True


def test_run_loop_stops_without_sleeping_after_max_cycles(monkeypatch):
    signer = Keypair()
    fake_agent = _FakeAgent()
    sleep_calls: list[float] = []

    monkeypatch.setattr("wzrd.loop.load_keypair", lambda keypair=None: signer)
    monkeypatch.setattr("wzrd.loop.WZRDAgent", lambda: fake_agent)
    monkeypatch.setattr("wzrd.loop._fetch_ccm_price", lambda: None)
    monkeypatch.setattr("wzrd.loop.shortlist", lambda task, limit=3: [])
    monkeypatch.setattr(
        "wzrd.loop.pick_details",
        lambda task: PickResult(
            model="moonshotai/Kimi-K2.5",
            signal_model="moonshotai/Kimi-K2.5",
            task=task,
            policy="strict",
            score=1.0,
            raw_score=1.0,
            trend="surging",
            confidence="high",
            action="candidate",
            platform="huggingface",
            reason="test signal",
        ),
    )
    monkeypatch.setattr("wzrd.loop.time.sleep", lambda seconds: sleep_calls.append(seconds))

    run_loop(tasks=["code"], cycle_seconds=30, max_cycles=1, quiet=True)

    assert fake_agent.auth_calls == 1
    assert fake_agent.claim_calls == 0
    assert fake_agent.report_calls == 1
    assert sleep_calls == []
