from __future__ import annotations

import json
from pathlib import Path

from osm_lead_source_service.dashboard import (
    build_dashboard_payload,
    load_dashboard_snapshot,
    render_dashboard,
)


def _valid_snapshot() -> dict[str, object]:
    return {
        "kind": "runtime-evidence",
        "generated_at": "2026-08-01T00:05:00Z",
        "region": "english-markets",
        "profile": "luxeillum",
        "profile_version": "0.1.0-draft",
        "report_hash": "a" * 64,
        "source_sha256": "b" * 64,
        "source_size_bytes": 123,
        "counts": {"active": 10, "review": 1, "excluded": 2, "out_of_scope": 100},
        "categories": {"Restaurant / cafe": 10},
        "coverage": {
            "configured_markets": 58,
            "completed_markets": 58,
            "failed_markets": 0,
            "configured_shards": 120,
            "completed_shards": 120,
            "failed_shards": 0,
        },
        "noco": {
            "comparison_completed": False,
            "exact_identity_matches": 0,
            "unmatched_identities": 0,
            "duplicate_row_excess_detected": False,
        },
        "run": {
            "cache_hit": False,
            "completed_at": "2026-08-01T00:05:00Z",
            "started_at": "2026-08-01T00:00:00Z",
            "status": "completed",
        },
    }


def test_release_snapshot_contains_accepted_act_evidence() -> None:
    snapshot, warning = load_dashboard_snapshot({})

    assert warning is None
    assert snapshot["region"] == "au-act"
    assert snapshot["report_hash"] == (
        "bdc4661686bde64905c1c6cce986b4c053f78eeb5a9b88381ae62e45d254e342"
    )
    assert snapshot["counts"] == {
        "active": 980,
        "review": 0,
        "excluded": 601,
        "out_of_scope": 2_716_858,
    }
    assert snapshot["noco"]["comparison_completed"] is True


def test_valid_runtime_snapshot_replaces_release_evidence(tmp_path: Path) -> None:
    path = tmp_path / "dashboard.json"
    path.write_text(json.dumps(_valid_snapshot()), encoding="utf-8")

    snapshot, warning = load_dashboard_snapshot(
        {"OSM_LEAD_SOURCE_DASHBOARD_SNAPSHOT_PATH": str(path)}
    )

    assert warning is None
    assert snapshot["kind"] == "runtime-evidence"
    assert snapshot["source_size_bytes"] == 123
    assert snapshot["noco"]["comparison_completed"] is False


def test_invalid_runtime_snapshot_falls_back_without_error_details(
    tmp_path: Path,
) -> None:
    path = tmp_path / "dashboard.json"
    path.write_text('{"unexpected":"secret-value"}', encoding="utf-8")

    snapshot, warning = load_dashboard_snapshot(
        {"OSM_LEAD_SOURCE_DASHBOARD_SNAPSHOT_PATH": str(path)}
    )

    assert snapshot["kind"] == "verified-release-evidence"
    assert warning == "Live worker evidence is unavailable; showing verified release evidence."
    assert "secret-value" not in warning


def test_dashboard_payload_reports_pending_live_comparison(tmp_path: Path) -> None:
    path = tmp_path / "dashboard.json"
    path.write_text(json.dumps(_valid_snapshot()), encoding="utf-8")
    payload = build_dashboard_payload(
        {
            "legacy_writer_disabled": False,
            "scheduler_enabled": True,
            "sidecar_configured": False,
            "stale_deletion_enabled": False,
            "write_runtime_armed": False,
        },
        {"OSM_LEAD_SOURCE_DASHBOARD_SNAPSHOT_PATH": str(path)},
    )
    readiness = payload["readiness"]

    assert isinstance(readiness, dict)
    assert readiness["live_worker"]["ready"] is True
    assert readiness["market_coverage"]["ready"] is True
    assert readiness["noco_comparison"]["ready"] is False
    assert readiness["monthly_scheduler"]["ready"] is True
    assert "Lead creation remains disabled" in payload["next_gate"]


def test_dashboard_html_is_self_contained_and_escapes_values() -> None:
    payload = build_dashboard_payload(
        {
            "environment": "production<script>",
            "legacy_writer_disabled": False,
            "mode": "shadow-read-only",
            "noco_write_enabled": False,
            "read_only": True,
            "release_sha": "abc123",
            "scheduler_enabled": False,
            "sidecar_configured": False,
            "stale_deletion_enabled": False,
            "version": "0.4.0",
            "write_runtime_armed": False,
        },
        {},
    )

    rendered = render_dashboard(payload).decode()

    assert "<!doctype html>" in rendered
    assert "OpenStreetMap Lead Generator" in rendered
    assert "980" in rendered
    assert "478" in rendered
    assert "production&lt;script&gt;" in rendered
    assert "production<script>" not in rendered
    assert "https://" not in rendered
