from __future__ import annotations

from pathlib import Path

from scripts.drawer_migration_lib import (
    SQLiteTemporalStore,
    build_migration_report,
    migrate_tenant,
)


def _seed_legacy_records(tenant_dir: Path) -> None:
    temporal = SQLiteTemporalStore(db_path=str(tenant_dir / "temporal.db"))
    try:
        temporal.set(
            "memory:cmd-1",
            {
                "id": "cmd-1",
                "content": "Always keep directives deterministic.",
                "context": "directives_policy",
                "importance": 0.9,
                "created_at": "2026-02-28T10:00:00Z",
            },
        )
        temporal.set(
            "memory:state-1",
            {
                "id": "state-1",
                "content": "Objective: ship migration report.",
                "context": "objectives",
                "importance": 0.8,
                "created_at": "2026-02-28T10:01:00Z",
            },
        )
        temporal.set(
            "memory:raw-1",
            {
                "id": "raw-1",
                "content": "Audit event: writeback request captured.",
                "context": "audit_log",
                "importance": 0.6,
                "created_at": "2026-02-28T10:02:00Z",
            },
        )
        temporal.set(
            "memory:know-1",
            {
                "id": "know-1",
                "content": "Use idempotency keys for payment confirmation.",
                "context": "knowledge_payment",
                "importance": 0.7,
                "created_at": "2026-02-28T10:03:00Z",
            },
        )
    finally:
        temporal.close()


def test_phase4_report_fails_before_migration(tmp_path):
    base_data_dir = tmp_path / "data"
    tenant_dir = base_data_dir / "tenants" / "tenantA"
    tenant_dir.mkdir(parents=True, exist_ok=True)
    _seed_legacy_records(tenant_dir)

    report = build_migration_report(
        base_data_dir=str(base_data_dir),
        verify_preservation=99.9,
        emit_checksums=True,
    )

    assert report["status"] == "FAIL"
    assert report["global"]["pre_total_records"] == 4
    assert report["global"]["post_numerator"] == 1
    assert report["global"]["verify_preservation_passed"] is False
    assert report["global"]["checksum_parity"]["knowledge"] is True
    assert report["global"]["checksum_parity"]["command"] is False


def test_phase4_migration_apply_and_report_passes(tmp_path):
    base_data_dir = tmp_path / "data"
    tenant_dir = base_data_dir / "tenants" / "tenantB"
    tenant_dir.mkdir(parents=True, exist_ok=True)
    _seed_legacy_records(tenant_dir)

    run = migrate_tenant(
        tenant_dir=tenant_dir,
        hat_id="hat_migrated_default",
        run_id="run_phase4_test",
        dry_run=False,
    )
    assert run["status"] == "MIGRATION_APPLIED"
    assert run["mapped_candidates"] == 3
    assert run["created"] == 3

    temporal = SQLiteTemporalStore(db_path=str(tenant_dir / "temporal.db"))
    try:
        assert temporal.get("drawer:hat_migrated_default:directives:active:migrated-cmd-1")
        assert temporal.get("drawer:hat_migrated_default:objectives:active:migrated-state-1")
        assert temporal.get("drawer:hat_migrated_default:raw_log:item:migrated-raw-1")
    finally:
        temporal.close()

    report = build_migration_report(
        base_data_dir=str(base_data_dir),
        verify_preservation=99.9,
        emit_checksums=True,
    )
    assert report["status"] == "PASS"
    assert report["global"]["pre_total_records"] == 4
    assert report["global"]["post_numerator"] == 4
    assert report["global"]["verify_preservation_passed"] is True
    assert report["global"]["checksum_parity_passed"] is True
