"""End-to-end local shadow-run CLI tests."""

from __future__ import annotations

import base64
import json
from pathlib import Path

from osm_lead_source_service.cli import main

_FIXTURE = Path(__file__).parents[1] / "fixtures" / "pbf" / "tiny.osm.pbf.b64"
_SHA256 = "1f181fa63b838de88c5c7d8ecff2a014ca52a9349c6470fd2656ad3c9e0ddb8c"


def _write_fixture(tmp_path: Path) -> tuple[Path, bytes]:
    payload = base64.b64decode(_FIXTURE.read_text(encoding="ascii").strip(), validate=True)
    pbf = tmp_path / "tiny.osm.pbf"
    pbf.write_bytes(payload)
    return pbf, payload


def _arguments(pbf: Path, payload: bytes, output: Path | str) -> list[str]:
    return [
        "shadow-run",
        "--pbf",
        str(pbf),
        "--sha256",
        _SHA256,
        "--size-bytes",
        str(len(payload)),
        "--region",
        "fixture-region",
        "--profile",
        "luxeillum",
        "--profile-version",
        "0.1.0-draft",
        "--country-code",
        "TH",
        "--calling-code",
        "66",
        "--output",
        str(output),
        "--max-file-size-bytes",
        "1024",
        "--max-objects",
        "10",
        "--max-total-tags",
        "1000",
        "--max-blob-size-bytes",
        "4096",
        "--max-uncompressed-blob-bytes",
        "4096",
        "--max-total-uncompressed-bytes",
        "4096",
        "--max-blob-count",
        "10",
        "--max-leads",
        "10",
        "--max-review-items",
        "10",
    ]


def test_shadow_run_writes_repeatable_atomic_report(tmp_path: Path, capsys: object) -> None:
    pbf, payload = _write_fixture(tmp_path)
    output = tmp_path / "shadow-report.json"
    arguments = _arguments(pbf, payload, output)

    assert main(arguments) == 0
    captured = capsys.readouterr()  # type: ignore[attr-defined]
    summary = json.loads(captured.out)
    report_text = output.read_text(encoding="utf-8")
    report = json.loads(report_text)
    assert report_text.endswith("\n")
    assert summary["lead_count"] == 3
    assert summary["review_count"] == 0
    assert summary["report_hash"] == report["report_hash"]
    assert report["state_counts"] == {"active": 3, "out_of_scope": 1}
    assert report["category_counts"] == {
        "Hospitality/Accommodation": 1,
        "Hospitality/Restaurant or cafe": 2,
    }
    assert [(lead["osm_type"], lead["osm_id"]) for lead in report["leads"]] == [
        ("node", 1),
        ("relation", 20),
        ("way", 10),
    ]
    assert output.stat().st_mode & 0o777 == 0o600

    assert main(arguments) == 2
    captured = capsys.readouterr()  # type: ignore[attr-defined]
    assert "output already exists" in captured.err
    assert output.read_text(encoding="utf-8") == report_text

    assert main(arguments + ["--overwrite"]) == 0
    capsys.readouterr()  # type: ignore[attr-defined]
    assert output.read_text(encoding="utf-8") == report_text


def test_shadow_run_can_emit_json_to_stdout(tmp_path: Path, capsys: object) -> None:
    pbf, payload = _write_fixture(tmp_path)
    assert main(_arguments(pbf, payload, "-")) == 0
    captured = capsys.readouterr()  # type: ignore[attr-defined]
    report = json.loads(captured.out)
    assert report["profile"] == {"id": "luxeillum", "version": "0.1.0-draft"}
    assert len(report["report_hash"]) == 64
    assert captured.err == ""


def test_shadow_run_rejects_bad_checksum_without_output(tmp_path: Path, capsys: object) -> None:
    pbf, payload = _write_fixture(tmp_path)
    output = tmp_path / "must-not-exist.json"
    arguments = _arguments(pbf, payload, output)
    checksum_index = arguments.index("--sha256") + 1
    arguments[checksum_index] = "0" * 64

    assert main(arguments) == 2
    captured = capsys.readouterr()  # type: ignore[attr-defined]
    assert "checksum" in captured.err.casefold()
    assert not output.exists()
