import json
import random
from types import SimpleNamespace

import numpy as np
import pytest
import torch

from pallet.experiments import train as training
from pallet.matrix import _is_completed


def test_resume_keeps_original_git_metadata_but_rejects_changed_source(tmp_path):
    from pallet.cli import _record_run_config
    path=tmp_path/'run.json'
    original={'source_snapshot_id':'same','annotation_sha256':'labels',
              'git_commit':'first','git_dirty':True}
    _record_run_config(path,original)
    _record_run_config(path,{**original,'git_commit':'docs-only','git_dirty':False})
    assert json.loads(path.read_text())==original
    with pytest.raises(ValueError,match='different label snapshot or configuration'):
        _record_run_config(path,{**original,'source_snapshot_id':'changed'})


class TinyDataset:
    def __init__(self, records, labels, normalization, **kwargs):
        self.rows = [(item, SimpleNamespace(boxes=[1],ignore_regions=[])) for item in records]

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, idx):
        value = idx + random.random() + np.random.random() + torch.rand(()).item()
        return (torch.full((4, 2, 2), value), torch.tensor([[0.5, 0.5, 0.2, 0.2]]),
                SimpleNamespace(frame_id=str(idx)))


class TinyDetector(torch.nn.Module):
    def __init__(self, **kwargs):
        super().__init__()
        self.weight = torch.nn.Parameter(torch.tensor(0.4))

    def loss(self, batch):
        # Same batch-scaled convention as Ultralytics.
        values = batch["img"][:, 0, 0, 0]
        return ((self.weight * values - 1) ** 2).sum(), {}


def test_interrupted_training_resumes_same_weights_and_scheduler(tmp_path, monkeypatch):
    torch.set_num_threads(1)
    monkeypatch.setattr(training, "PalletDataset", TinyDataset)
    monkeypatch.setattr(training, "PalletDetector", TinyDetector)
    monkeypatch.setattr(training, "evaluate", lambda *args, **kwargs: {"AP50_95": 0.5})
    args = (list(range(5)), [0], None, SimpleNamespace(mean=1), tmp_path / "continuous")
    options = dict(pretrained=None, epochs=3, batch_size=2, effective_batch=4,
                   device="cpu", size=2, warmup_epochs=1)
    training.train_yolo(*args, **options)
    complete = torch.load(tmp_path / "continuous" / "last.pt", weights_only=False)

    calls = 0

    def interrupted(*args, **kwargs):
        nonlocal calls
        calls += 1
        if calls == 2:
            raise RuntimeError("interrupted")
        return {"AP50_95": 0.5}

    monkeypatch.setattr(training, "evaluate", interrupted)
    resumed_args = (*args[:-1], tmp_path / "resumed")
    with pytest.raises(RuntimeError, match="interrupted"):
        training.train_yolo(*resumed_args, **options)
    assert not (tmp_path / "resumed" / "completed.json").exists()
    assert (tmp_path / "resumed" / "last.pt").exists()
    monkeypatch.setattr(training, "evaluate", lambda *args, **kwargs: {"AP50_95": 0.5})
    training.train_yolo(*resumed_args, **options)
    resumed = torch.load(tmp_path / "resumed" / "last.pt", weights_only=False)
    torch.testing.assert_close(complete["model"]["weight"], resumed["model"]["weight"], rtol=0, atol=0)
    assert complete["scheduler"]["last_epoch"] == resumed["scheduler"]["last_epoch"]
    marker = json.loads((tmp_path / "resumed" / "completed.json").read_text())
    assert marker["completed_epochs"] == 3 and marker["stopped_reason"] == "epochs"
    assert _is_completed(tmp_path / "resumed", 3)
    (tmp_path / "resumed" / "completed.json").unlink()
    assert not _is_completed(tmp_path / "resumed", 3)


def test_partial_window_uses_actual_example_count(tmp_path, monkeypatch):
    monkeypatch.setattr(training, "PalletDataset", TinyDataset)
    monkeypatch.setattr(training, "PalletDetector", TinyDetector)
    monkeypatch.setattr(training, "evaluate", lambda *args, **kwargs: {"AP50_95": 0.5})
    training.train_yolo(list(range(5)), [0], None, SimpleNamespace(mean=1),
                        tmp_path / "run", pretrained=None, epochs=1, batch_size=2,
                        effective_batch=4, device="cpu", size=2)
    saved = torch.load(tmp_path / "run" / "last.pt", weights_only=False)
    assert saved["scheduler"]["last_epoch"] == 2


def test_best_publication_crash_restores_last_referenced_best(tmp_path, monkeypatch):
    monkeypatch.setattr(training, "PalletDataset", TinyDataset)
    monkeypatch.setattr(training, "PalletDetector", TinyDetector)
    scores = iter([0.1, 0.9])
    monkeypatch.setattr(training, "evaluate", lambda *a, **k: {"AP50_95": next(scores)})
    original_replace = training.os.replace
    last_writes = 0

    def crash_after_new_best(source, target):
        nonlocal last_writes
        if str(target).endswith('/last.pt'):
            last_writes += 1
            if last_writes == 2:
                raise RuntimeError('publication interrupted')
        return original_replace(source, target)

    monkeypatch.setattr(training.os, 'replace', crash_after_new_best)
    args = ([0, 1], [0], None, SimpleNamespace(mean=1), tmp_path/'run')
    options = dict(pretrained=None, epochs=2, batch_size=1, effective_batch=1, device='cpu', size=2)
    with pytest.raises(RuntimeError, match='publication interrupted'):
        training.train_yolo(*args, **options)
    saved = torch.load(tmp_path/'run'/'last.pt', weights_only=False)
    assert saved['best_ap'] == 0.1
    assert training._checkpoint_digest(tmp_path/'run'/'best.pt') != saved['best_checkpoint_sha256']
    monkeypatch.setattr(training.os, 'replace', original_replace)
    training._recover_best(saved, tmp_path/'run')
    assert training._checkpoint_digest(tmp_path/'run'/'best.pt') == saved['best_checkpoint_sha256']
    monkeypatch.setattr(training, 'evaluate', lambda *a, **k: {'AP50_95': 0.9})
    training.train_yolo(*args, **options)
    resumed = torch.load(tmp_path/'run'/'last.pt', weights_only=False)
    assert resumed['best_ap'] == 0.9
    assert training._checkpoint_digest(tmp_path/'run'/'best.pt') == resumed['best_checkpoint_sha256']


def test_legacy_improvement_can_repair_missing_best(tmp_path):
    saved = {'stale': 0, 'best_ap': 0.7, 'model': {'weight': torch.tensor(1.)}}
    training._recover_best(saved, tmp_path)
    assert torch.load(tmp_path/'best.pt', weights_only=False)['best_ap'] == 0.7
    with pytest.raises(ValueError, match='unavailable or changed'):
        training._recover_best({**saved, 'best_checkpoint_sha256': 'corrupted'}, tmp_path)
