"""Tests for milco history handling corrupt index lines."""

import json
from milco.cli import main


def test_corrupt_lines_skipped(tmp_path, monkeypatch, capsys):
    runs_dir = tmp_path / "runs"
    runs_dir.mkdir()

    valid1 = json.dumps(
        {
            "timestamp": "2026-01-01T00:00:00Z",
            "run_id": "ok1",
            "command": "run",
            "mode": "dry_run",
            "decision": "PASS",
            "exit_code": 0,
            "git": {"commit": None, "branch": None},
            "paths": {"run_dir": "runs/ok1", "manifest": "runs/ok1/manifest.json"},
        }
    )
    valid2 = json.dumps(
        {
            "timestamp": "2026-01-02T00:00:00Z",
            "run_id": "ok2",
            "command": "run",
            "mode": "dry_run",
            "decision": "FAIL",
            "exit_code": 1,
            "git": {"commit": None, "branch": None},
            "paths": {"run_dir": "runs/ok2", "manifest": "runs/ok2/manifest.json"},
        }
    )
    corrupt = "NOT VALID JSON {{{"

    content = "\n".join([valid1, corrupt, valid2]) + "\n"
    (runs_dir / "index.jsonl").write_text(content, encoding="utf-8")

    monkeypatch.chdir(tmp_path)
    exit_code = main(["history"])
    captured = capsys.readouterr()

    assert exit_code == 0

    # Both valid records shown
    assert "ok1" in captured.out
    assert "ok2" in captured.out

    # Corrupt line reported
    assert "Skipped 1 corrupt" in captured.out


def test_corrupt_warning_on_stderr(tmp_path, monkeypatch, capsys):
    runs_dir = tmp_path / "runs"
    runs_dir.mkdir()

    valid = json.dumps(
        {
            "timestamp": "2026-01-01T00:00:00Z",
            "run_id": "ok",
            "command": "run",
            "mode": "dry_run",
            "decision": "PASS",
            "exit_code": 0,
            "git": {"commit": None, "branch": None},
            "paths": {"run_dir": "runs/ok", "manifest": "runs/ok/manifest.json"},
        }
    )
    content = valid + "\nBAD LINE\n"
    (runs_dir / "index.jsonl").write_text(content, encoding="utf-8")

    monkeypatch.chdir(tmp_path)
    main(["history"])
    captured = capsys.readouterr()

    assert "Warning" in captured.err or "corrupt" in captured.err.lower()


def test_all_corrupt_shows_no_matching(tmp_path, monkeypatch, capsys):
    runs_dir = tmp_path / "runs"
    runs_dir.mkdir()
    (runs_dir / "index.jsonl").write_text("bad1\nbad2\n", encoding="utf-8")

    monkeypatch.chdir(tmp_path)
    exit_code = main(["history"])
    captured = capsys.readouterr()

    assert exit_code == 0
    assert "No matching runs" in captured.out
    assert "Skipped 2 corrupt" in captured.out
