import json
from pathlib import Path

import pytest
from click.testing import CliRunner

from cyclone.cli import main
from cyclone.parsers.payer import PayerConfig


FIXTURE = Path(__file__).parent / "fixtures" / "minimal_837p.txt"


def test_cli_parse_837_writes_outputs(tmp_path: Path):
    runner = CliRunner()
    result = runner.invoke(main, ["parse-837", str(FIXTURE), "--output-dir", str(tmp_path)])
    assert result.exit_code == 0, result.output
    written = list(tmp_path.glob("claim-*.json"))
    assert len(written) == 1
    summary = json.loads((tmp_path / "summary.json").read_text())
    assert summary["total_claims"] == 1
    assert summary["passed"] == 1


def test_cli_parse_837_with_strict(tmp_path: Path):
    runner = CliRunner()
    result = runner.invoke(main, ["parse-837", str(FIXTURE), "--output-dir", str(tmp_path), "--strict"])
    assert result.exit_code == 0
    # Strict should not change anything on a passing claim
    summary = json.loads((tmp_path / "summary.json").read_text())
    assert summary["passed"] == 1


def test_cli_parse_837_with_no_raw_segments(tmp_path: Path):
    runner = CliRunner()
    result = runner.invoke(main, ["parse-837", str(FIXTURE), "--output-dir", str(tmp_path), "--no-raw-segments"])
    assert result.exit_code == 0
    data = json.loads(next(tmp_path.glob("claim-*.json")).read_text())
    assert data["raw_segments"] == []


def test_cli_unknown_payer_uses_generic(tmp_path: Path):
    runner = CliRunner()
    result = runner.invoke(main, ["parse-837", str(FIXTURE), "--output-dir", str(tmp_path), "--payer", "generic_837p"])
    assert result.exit_code == 0


def test_cli_missing_file_exits_2(tmp_path: Path):
    runner = CliRunner()
    result = runner.invoke(main, ["parse-837", "/no/such/file.txt", "--output-dir", str(tmp_path)])
    assert result.exit_code == 2


@pytest.mark.skipif(
    not (Path(__file__).parent.parent.parent / "docs" / "prodfiles" / "837p-from-axiscare").exists(),
    reason="prodfile corpus not present",
)
def test_cli_runs_against_prodfiles(tmp_path: Path):
    """Smoke test: run the CLI against a real production file if available."""
    from glob import glob
    runner = CliRunner()
    corpus = Path(__file__).parent.parent.parent / "docs" / "prodfiles" / "837p-from-axiscare"
    files = sorted(glob(str(corpus / "*.txt")))
    if not files:
        pytest.skip("no prodfile .txt files in corpus")
    sample = files[0]
    result = runner.invoke(main, ["parse-837", sample, "--output-dir", str(tmp_path)])
    assert result.exit_code == 0, result.output
    summary = json.loads((tmp_path / "summary.json").read_text())
    assert summary["total_claims"] >= 1
