"""Tests for canonical KB claim routes."""

from __future__ import annotations

import asyncio
import json
import sys
from pathlib import Path

import pytest

pytest.importorskip("aiohttp")

from aiohttp import web
from aiohttp.test_utils import make_mocked_request

REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "diagnostics"))

import kb_claim_routes as routes  # noqa: E402


CLAIM_ID = "d0000000-0000-0000-0000-000000000005"
CONNECTED_ID = "e0000000-0000-0000-0000-000000000006"


def _claim_data():
    return {
        "claim": {
            "id": CLAIM_ID,
            "type": "strategy_kernel",
            "text": "Claims should be falsifiable enough to support review.",
            "status": "open",
            "confidence": "0.72",
            "tags": ["claims", "review"],
            "created_at": "2026-07-09T00:00:00Z",
            "updated_at": "2026-07-09T00:00:00Z",
        },
        "evidence": [
            {
                "role": "grounds",
                "weight": "0.8",
                "source_type": "telegram",
                "url": "https://example.test/source",
                "storage_path": None,
                "excerpt": "m3taversal asked Leo to split a broad claim into atomic claims.",
            }
        ],
        "edges": [
            {
                "direction": "outgoing",
                "edge_type": "supports",
                "connected_id": CONNECTED_ID,
                "connected_text": "Reviewable claims need supporting evidence and edges.",
                "connected_status": "open",
            }
        ],
    }


def test_claim_link_html_links_valid_claim_ids() -> None:
    html = routes.claim_link_html(CLAIM_ID)

    assert f'href="/kb/claims/{CLAIM_ID}"' in html
    assert f"<code>{CLAIM_ID}</code>" in html


def test_render_kb_claim_page_shows_body_evidence_and_linked_edges() -> None:
    html = routes.render_kb_claim_page(_claim_data())

    assert "Claims should be falsifiable enough to support review." in html
    assert "m3taversal asked Leo" in html
    assert f'href="/kb/claims/{CONNECTED_ID}"' in html
    assert "<code>supports</code>" in html
    assert "<code>open</code>" in html


def test_api_kb_claim_uses_loader_and_returns_claim_graph() -> None:
    app = web.Application()
    app[routes.KB_CLAIM_LOADER_KEY] = lambda claim_id: _claim_data() if claim_id == CLAIM_ID else None
    req = make_mocked_request(
        "GET",
        f"/api/kb/claims/{CLAIM_ID}",
        app=app,
        match_info={"claim_id": CLAIM_ID},
    )

    response = asyncio.run(routes.handle_api_kb_claim(req))
    data = json.loads(response.body.decode())

    assert response.status == 200
    assert data["claim"]["id"] == CLAIM_ID
    assert data["edges"][0]["connected_id"] == CONNECTED_ID
