from __future__ import annotations

import importlib
import os
import sys
from pathlib import Path

from scripts.drawer_migration_lib import SQLiteTemporalStore, migrate_tenant
from scripts.migration_rollback_drill import build_rollback_drill_snapshot


def _seed_legacy_memory(tenant_dir: Path, key: str, memory_id: str, content: str, context: str) -> None:
    temporal = SQLiteTemporalStore(db_path=str(tenant_dir / "temporal.db"))
    try:
        temporal.set(
            key,
            {
                "id": memory_id,
                "content": content,
                "context": context,
                "importance": 0.8,
                "created_at": "2026-03-01T00:00:00Z",
            },
        )
    finally:
        temporal.close()


def test_phase5_alert_evaluator_flags_threshold_violations():
    if "api.main" in sys.modules:
        del sys.modules["api.main"]
    api_main = importlib.import_module("api.main")

    report = {
        "status": "FAIL",
        "tenants_scanned": 2,
        "global": {
            "preservation_pct": 97.0,
            "checksum_parity": {
                "command": True,
                "state": False,
                "knowledge": True,
                "raw": False,
            },
        },
        "tenants": [
            {
                "tenant_id": "aaa",
                "preservation_pct": 95.0,
                "checksum_parity": {"command": True, "state": False, "knowledge": True, "raw": True},
            },
            {
                "tenant_id": "bbb",
                "preservation_pct": 99.95,
                "checksum_parity": {"command": True, "state": True, "knowledge": True, "raw": True},
            },
        ],
    }
    alerts = api_main._evaluate_migration_alerts(
        report,
        thresholds={
            "min_preservation_pct": 99.9,
            "max_failed_tenants": 0,
            "max_checksum_mismatch_classes": 0,
        },
    )
    assert alerts["status"] == "ALERT"
    codes = {row["code"] for row in alerts["alerts"]}
    assert "GLOBAL_PRESERVATION_BELOW_TARGET" in codes
    assert "GLOBAL_CHECKSUM_MISMATCH_LIMIT_EXCEEDED" in codes
    assert "FAILED_TENANT_COUNT_EXCEEDED" in codes


def test_phase5_admin_migration_telemetry_payload_ok_after_apply(tmp_path):
    base_dir = tmp_path / "tenant_data"
    tenant_id = "phase5tenant000001"
    tenant_dir = base_dir / "tenants" / tenant_id
    tenant_dir.mkdir(parents=True, exist_ok=True)

    _seed_legacy_memory(
        tenant_dir=tenant_dir,
        key="memory:phase5-1",
        memory_id="phase5-1",
        content="Track migration telemetry endpoint status.",
        context="objective_runtime",
    )
    migrate_tenant(
        tenant_dir=tenant_dir,
        hat_id="hat_phase5_ops",
        run_id="run_phase5_ops",
        dry_run=False,
        include_knowledge_shadow=False,
    )

    os.environ["MEMORY_DATA_DIR"] = str(base_dir)
    if "api.main" in sys.modules:
        del sys.modules["api.main"]
    api_main = importlib.import_module("api.main")

    payload = api_main._admin_migration_telemetry_payload(
        verify_preservation=99.9,
        emit_checksums=False,
        tenant_filters=[tenant_id],
        dry_run=True,
        thresholds={
            "min_preservation_pct": 99.9,
            "max_failed_tenants": 0,
            "max_checksum_mismatch_classes": 0,
        },
    )
    assert payload["status"] == "DRY_RUN_OK"
    assert payload["alert_status"] == "OK"
    assert payload["summary"]["tenants_scanned"] == 1
    assert payload["summary"]["failed_tenant_count"] == 0
    assert payload["report"]["meta"]["base_data_dir"] == str(base_dir)


def test_phase5_rollback_drill_snapshot_ready_after_migration(tmp_path):
    base_dir = tmp_path / "tenant_data"
    tenant_id = "phase5tenant000002"
    tenant_dir = base_dir / "tenants" / tenant_id
    tenant_dir.mkdir(parents=True, exist_ok=True)

    _seed_legacy_memory(
        tenant_dir=tenant_dir,
        key="memory:phase5-2",
        memory_id="phase5-2",
        content="Rollback drill validation record.",
        context="state_runtime",
    )
    migrate_tenant(
        tenant_dir=tenant_dir,
        hat_id="hat_phase5_ops",
        run_id="run_phase5_drill",
        dry_run=False,
        include_knowledge_shadow=False,
    )

    snapshot = build_rollback_drill_snapshot(
        base_data_dir=str(base_dir),
        tenant_filters=[tenant_id],
        verify_preservation=99.9,
        require_archived_min=0,
    )
    assert snapshot["status"] == "DRILL_READY"
    assert snapshot["tenants_scanned"] == 1
    assert snapshot["tenants_ready"] == 1
    assert snapshot["tenants"][0]["ready"] is True
