#!/usr/bin/env python3
from __future__ import annotations

import json
import os
import sys
import tempfile
import unittest
from pathlib import Path


HERE = Path(__file__).resolve().parent
TEST_ROOT = Path(tempfile.mkdtemp(prefix="iterfact_artifact_versions_"))
(TEST_ROOT / "generated").mkdir(parents=True, exist_ok=True)
(TEST_ROOT / "analytics").mkdir(parents=True, exist_ok=True)

os.environ["ITERFACT_OUTPUT_DIR"] = str(TEST_ROOT / "generated")
os.environ["ITERFACT_ANALYTICS_DIR"] = str(TEST_ROOT / "analytics")
os.environ["ITERFACT_HEADLESS_VALIDATION_ENABLED"] = "0"
os.environ["ITERFACT_LIBRARY_PREVIEW_CAPTURE_ENABLED"] = "0"
os.environ["ITERFACT_PUBLIC_ARTIFACT_BASE_URL"] = "https://a.iterfact.test"
os.environ["ANTHROPIC_API_KEY"] = ""

if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

import server as mcp_server  # noqa: E402


ARTIFACT_ID = "artifact-version-ledger"


def _write_state() -> None:
    state = {
        "artifact_id": ARTIFACT_ID,
        "created_at": "2026-03-22T12:00:00+00:00",
        "updated_at": "2026-03-24T12:00:00+00:00",
        "artifact_status": "published",
        "title": "IterFact Version Ledger",
        "plan": {"wrapper": {"engine": "12"}, "sections": []},
        "current": {
            "html_file": "20260324-120000-iterfact-version-ledger-v3.html",
            "preview_url": "https://a.iterfact.test/generated/artifact-version-ledger/20260324-120000-iterfact-version-ledger-v3.html",
            "object_key": "generated/artifact-version-ledger/20260324-120000-iterfact-version-ledger-v3.html",
            "quality_score": 95,
            "warnings": [],
            "updated_at": "2026-03-24T12:00:00+00:00",
            "published_at": "2026-03-24T12:00:00+00:00",
            "generation_mode": "planned_render",
            "version_title": "IterFact Version Ledger",
        },
        "revision_history": [
            {
                "html_file": "20260323-120000-iterfact-version-ledger-v2.html",
                "preview_url": "https://a.iterfact.test/generated/artifact-version-ledger/20260323-120000-iterfact-version-ledger-v2.html",
                "object_key": "generated/artifact-version-ledger/20260323-120000-iterfact-version-ledger-v2.html",
                "quality_score": 90,
                "warnings": [{"type": "editorial_soft_warning"}],
                "updated_at": "2026-03-23T12:00:00+00:00",
                "published_at": "2026-03-23T12:00:00+00:00",
                "superseded_at": "2026-03-24T12:00:00+00:00",
                "generation_mode": "section_regeneration",
                "regeneration_context": {"section_index": 2, "section_title": "Momentum"},
                "version_title": "IterFact Version Ledger",
            },
            {
                "html_file": "20260322-120000-iterfact-version-ledger-v1.html",
                "preview_url": "https://a.iterfact.test/generated/artifact-version-ledger/20260322-120000-iterfact-version-ledger-v1.html",
                "object_key": "generated/artifact-version-ledger/20260322-120000-iterfact-version-ledger-v1.html",
                "quality_score": 88,
                "warnings": [],
                "updated_at": "2026-03-22T12:00:00+00:00",
                "published_at": "2026-03-22T12:00:00+00:00",
                "superseded_at": "2026-03-23T12:00:00+00:00",
                "generation_mode": "admin_passthrough_html",
                "version_title": "IterFact Version Ledger",
            },
        ],
    }
    state_path = mcp_server.artifact_state_path(ARTIFACT_ID)
    state_path.parent.mkdir(parents=True, exist_ok=True)
    state_path.write_text(json.dumps(state, ensure_ascii=True, indent=2), encoding="utf-8")


class ArtifactVersionTests(unittest.TestCase):
    def setUp(self) -> None:
        _write_state()

    def test_build_versions_response_assigns_primary_and_numbers(self) -> None:
        state = mcp_server.load_artifact_state(ARTIFACT_ID)
        payload = mcp_server.build_artifact_versions_response(state)

        self.assertEqual(payload["version_count"], 3)
        self.assertEqual(payload["primary_html_file"], "20260324-120000-iterfact-version-ledger-v3.html")
        self.assertEqual(payload["primary_version"]["version_number"], 3)
        self.assertTrue(payload["primary_version"]["is_primary"])
        self.assertEqual(payload["versions"][1]["reason"], "Section 2 refreshed: Momentum")

    def test_promoting_older_version_updates_primary_preference(self) -> None:
        state = mcp_server.set_artifact_primary_version(
            ARTIFACT_ID,
            "20260322-120000-iterfact-version-ledger-v1.html",
        )
        payload = mcp_server.build_artifact_versions_response(state)

        self.assertEqual(payload["primary_html_file"], "20260322-120000-iterfact-version-ledger-v1.html")
        self.assertEqual(
            payload["primary_version"]["preview_url"],
            "https://a.iterfact.test/generated/artifact-version-ledger/20260322-120000-iterfact-version-ledger-v1.html",
        )

    def test_public_iteration_toggle_persists(self) -> None:
        state = mcp_server.set_artifact_public_iteration_visibility(
            ARTIFACT_ID,
            show_public_iterations=True,
        )
        payload = mcp_server.build_artifact_versions_response(state)

        self.assertTrue(payload["show_public_iterations"])
        self.assertEqual(
            payload["public_iterations_url"],
            f"{mcp_server.SETTINGS.public_app_base_url}/artifacts/{ARTIFACT_ID}/iterations",
        )


if __name__ == "__main__":
    unittest.main()
