from pathlib import Path
from types import SimpleNamespace
import json

import joblib
import numpy as np
import pandas as pd
import pytest

from suite19_resume import (
    build_salvage_manifest,
    verify_salvage_manifest,
)


SEEDS = [42, 43, 44]


def _fake_rep(path: Path, production=False):
    path.parent.mkdir(parents=True, exist_ok=True)

    obj = SimpleNamespace(
        signature="valid-signature",
        chronology_violations=0,
        hist_available=np.ones(20, dtype=bool),
        target_available=(
            np.ones(10, dtype=bool)
            if production
            else None
        ),
    )

    joblib.dump(obj, path)


def _fake_probe(path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)

    obj = SimpleNamespace(
        chronology_violations=0,
        backend={
            "committee_residual":
                "suite17_exact_newton_hgb"
        },
    )

    joblib.dump(obj, path)


def _write_safe_audit(path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)

    pd.DataFrame([
        {
            "scope": "hist",
            "available": True,
            "strict_train_before_query": True,
        },
        {
            "scope": "target",
            "available": True,
            "strict_train_before_query": True,
        },
    ]).to_csv(path, index=False)


def _make_complete_encoder(
    fold_dir: Path,
    encoder: str,
    selection_candidates: int,
):
    cache = fold_dir / "cache"
    probes = fold_dir / "probe_cache"

    # Historical candidate ledgers.
    for i in range(selection_candidates):
        _fake_rep(
            cache
            / f"{encoder}_selection_{i:014x}.joblib",
            production=False,
        )

        _fake_probe(
            probes
            / f"{encoder}_{1000+i:014x}.joblib"
        )

    # Production representations and probes.
    for i, seed in enumerate(SEEDS):
        _fake_rep(
            cache
            / f"{encoder}_production_{seed:014x}.joblib",
            production=True,
        )

        _fake_probe(
            probes
            / f"{encoder}_{2000+i:014x}.joblib"
        )

        sd = fold_dir / encoder / f"seed_{seed}"

        _write_safe_audit(
            sd / "chronology_audit.csv"
        )

        _write_safe_audit(
            sd / "probe_chronology_audit.csv"
        )

        (sd / "model_metadata.json").write_text(
            json.dumps({"seed": seed}),
            encoding="utf-8",
        )

    pd.DataFrame([
        {
            "candidate": i + 1,
            "status": "ok",
            "score": 0.001,
        }
        for i in range(selection_candidates)
    ]).to_csv(
        fold_dir
        / f"{encoder}_selection_candidates.csv",
        index=False,
    )

    (
        fold_dir
        / f"{encoder}_selected_config.json"
    ).write_text(
        json.dumps(
            {
                "encoder": encoder,
                "selected_config": {
                    "latent_dim": 32,
                },
            }
        ),
        encoding="utf-8",
    )

    metric_rows = []

    for seed in SEEDS:
        metric_rows.append(
            {
                "seed": seed,
                "encoder": encoder,
                "model": "committee_residual",
                "ap": 0.25,
            }
        )

    pd.DataFrame(metric_rows).to_csv(
        fold_dir
        / encoder
        / "seed_target_metrics.csv",
        index=False,
    )


def test_complete_branch_is_detected(tmp_path):
    fold = tmp_path / "fold_1"

    _make_complete_encoder(
        fold,
        "tabm",
        selection_candidates=2,
    )

    manifest = build_salvage_manifest(
        out_dir=tmp_path,
        fold=1,
        encoders=["tabm"],
        seeds=SEEDS,
        validate_joblib=True,
    )

    assert (
        manifest["branches"]["tabm"]["status"]
        == "complete"
    )

    assert (
        manifest["branches"]["tabm"]
        ["production_seed_count"]
        == 3
    )

    assert len(
        manifest["immutable_artifacts"]
    ) > 0


def test_missing_production_seed_is_partial(tmp_path):
    fold = tmp_path / "fold_1"

    _make_complete_encoder(
        fold,
        "tabm",
        selection_candidates=2,
    )

    # Remove one expensive production cache.
    for p in (
        fold / "cache"
    ).glob("tabm_production_*.joblib"):
        p.unlink()
        break

    manifest = build_salvage_manifest(
        out_dir=tmp_path,
        fold=1,
        encoders=["tabm"],
        seeds=SEEDS,
        validate_joblib=True,
    )

    assert (
        manifest["branches"]["tabm"]["status"]
        != "complete"
    )


def test_chronology_violation_prevents_complete(
    tmp_path,
):
    fold = tmp_path / "fold_1"

    _make_complete_encoder(
        fold,
        "tabm",
        selection_candidates=2,
    )

    bad = (
        fold
        / "tabm"
        / "seed_42"
        / "chronology_audit.csv"
    )

    pd.DataFrame([
        {
            "available": True,
            "strict_train_before_query": False,
        }
    ]).to_csv(
        bad,
        index=False,
    )

    manifest = build_salvage_manifest(
        out_dir=tmp_path,
        fold=1,
        encoders=["tabm"],
        seeds=SEEDS,
        validate_joblib=True,
    )

    assert (
        manifest["branches"]["tabm"]["status"]
        == "unsafe"
    )


def test_manifest_detects_mutated_cache(tmp_path):
    fold = tmp_path / "fold_1"

    _make_complete_encoder(
        fold,
        "tabm",
        selection_candidates=2,
    )

    manifest = build_salvage_manifest(
        out_dir=tmp_path,
        fold=1,
        encoders=["tabm"],
        seeds=SEEDS,
        validate_joblib=True,
    )

    manifest_path = (
        fold
        / "salvage"
        / "manifest.json"
    )

    manifest_path.parent.mkdir(
        parents=True,
        exist_ok=True,
    )

    manifest_path.write_text(
        json.dumps(manifest, indent=2),
        encoding="utf-8",
    )

    victim = Path(
        manifest["immutable_artifacts"][0]["path"]
    )

    with victim.open("ab") as f:
        f.write(b"mutation")

    result = verify_salvage_manifest(
        manifest_path
    )

    assert not result["ok"]
    assert result["mismatches"]