"""Additional tests for registry fallback and edge paths."""

from __future__ import annotations

import base64
from pathlib import Path
from types import SimpleNamespace

import pytest

import evaluation.registry as reg_mod
from evaluation.config import ClientMode
from evaluation.models import PhaseConfig, ProblemConfig
from evaluation.registry import ProblemRegistry, build_artifact_from_dir


def _problem() -> ProblemConfig:
    return ProblemConfig(
        title="Maze Exploration",
        level="Easy",
        phases=[PhaseConfig(phase_order=1, phase_level="Easy", phase_name="p1")],
    )


def setup_function() -> None:
    ProblemRegistry._instance = None


def test_build_artifact_from_dir_and_registry_helpers(tmp_path) -> None:
    root = tmp_path / "problem"
    root.mkdir()
    (root / "a.txt").write_text("a", encoding="utf-8")
    (root / "b.py").write_text("print(1)", encoding="utf-8")
    b64 = build_artifact_from_dir(root)
    assert base64.b64decode(b64)

    r = ProblemRegistry(mode=ClientMode.USER, api_key="k", backend_url="http://b")
    p = _problem()
    r.register(p)
    assert r.get("Maze Exploration") is p
    assert r.get("Nope") is None
    assert r.get_phase("Maze Exploration", 1) is not None
    assert r.get_phase("Maze Exploration", 99) is None
    assert "Maze Exploration" in r.list_all()
    assert r._get_sync_endpoint().endswith("/api/v1/problems/register")
    assert r._get_sync_headers()["X-API-Key"] == "k"


def test_registry_init_instance_and_sync_all(monkeypatch) -> None:
    ProblemRegistry.init(mode=ClientMode.WORKER, api_key="ik", backend_url="http://b")
    inst = ProblemRegistry.instance()
    assert inst.mode == ClientMode.WORKER
    assert inst._get_sync_endpoint().endswith("/internal/register-problem")
    assert inst._get_sync_headers()["X-Internal-Key"] == "ik"

    r = ProblemRegistry(mode=ClientMode.USER, api_key="k", backend_url="http://b")
    p = _problem()
    r.register(p)
    monkeypatch.setattr(r, "sync_to_db", lambda definition, revision_title="", revision_description="": {1: True})
    out = r.sync_all()
    assert out["Maze Exploration"] == {1: True}


def test_registry_phase_exists_and_checksum_error_paths(monkeypatch, dummy_response_cls) -> None:
    r = ProblemRegistry(mode=ClientMode.WORKER, api_key="ik", backend_url="http://b")

    monkeypatch.setattr(
        reg_mod.requests,
        "post",
        lambda *args, **kwargs: dummy_response_cls(500, text="err"),
    )
    assert r._get_existing_checksum("Maze", 1) == ""
    assert r._phase_exists("Maze", 1) is False

    monkeypatch.setattr(
        reg_mod.requests,
        "post",
        lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("boom")),
    )
    assert r._get_existing_checksum("Maze", 1) == ""
    assert r._phase_exists("Maze", 1) is False

