"""Tests for generate_run orchestrator (no-invoke path)."""

import json
from pathlib import Path

import pytest

from pipeline.generate import generate_run

from tests.test_adapter import _seed_run_dir  # reuse Step-4 fixture


def test_generate_run_no_invoke_writes_adapter_input(tmp_path: Path) -> None:
    """invoke=False should still build adapter + persist input but skip Mantara."""
    run_dir = _seed_run_dir(tmp_path)
    report = generate_run(run_dir, invoke=False)

    assert report["adapter"]["system_name"] == "Test Order System"
    assert report["mantara"]["status"] == "skipped"
    assert report["mantara"]["skip_reason"] == "invoke=False"

    # step5_input.txt persisted
    schema_dir = run_dir / "schema"
    assert (schema_dir / "step5_input.txt").exists()
    # No Mantara outputs
    assert not (schema_dir / "schema.json").exists()
    assert not (schema_dir / "schema.sql").exists()
    # But the report exists
    assert (schema_dir / "step5_report.json").exists()
    report_disk = json.loads((schema_dir / "step5_report.json").read_text())
    assert report_disk["adapter"]["schema_name"] == report["adapter"]["schema_name"]


def test_generate_run_fails_on_missing_step4(tmp_path: Path) -> None:
    """Should refuse to run if entities.json from Step 4 is missing."""
    run_dir = tmp_path / "runs" / "empty"
    (run_dir / "cir").mkdir(parents=True)
    (run_dir / "cir" / "enriched_cir.json").write_text(json.dumps({
        "entities": [{"name": "X"}],
        "manifest": {"name": "X", "domain": "x", "type": "web"},
        "run_id": "empty",
    }))
    (run_dir / "prd").mkdir(parents=True)
    # No PRD or entities.json
    with pytest.raises(FileNotFoundError, match="entities.json"):
        generate_run(run_dir, invoke=False)


def test_generate_run_fails_on_zero_entities(tmp_path: Path) -> None:
    run_dir = tmp_path / "runs" / "zero"
    (run_dir / "cir").mkdir(parents=True)
    (run_dir / "cir" / "enriched_cir.json").write_text(json.dumps({
        "entities": [],
        "manifest": {"name": "X", "domain": "x", "type": "web"},
        "run_id": "zero",
    }))
    with pytest.raises(ValueError, match="No entities"):
        generate_run(run_dir, invoke=False)


def test_generate_run_with_no_prd_shrinks_input(tmp_path: Path) -> None:
    run_dir = _seed_run_dir(tmp_path)
    with_prd = generate_run(run_dir, invoke=False, include_prd=True)
    # Re-create run_dir for second run (first one wrote schema/)
    run_dir2 = _seed_run_dir(tmp_path / "second")
    without_prd = generate_run(run_dir2, invoke=False, include_prd=False)
    assert with_prd["adapter"]["input_chars"] >= without_prd["adapter"]["input_chars"]
