import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[1]
FIXTURE = REPO_ROOT / "tests" / "fixtures" / "planner_core_fixture.json"


def _py() -> str:
    return os.environ.get("PYTHON", "python3")


class TestPlanOpsToolContract(unittest.TestCase):
    def test_plan_ops_emits_overrides(self) -> None:
        payload = json.loads(FIXTURE.read_text(encoding="utf-8"))
        with tempfile.TemporaryDirectory() as td:
            td = Path(td)
            payload_path = td / "payload.json"
            selected_path = td / "selected.json"
            overrides_path = td / "overrides.json"

            payload_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
            selected_path.write_text(json.dumps(["a", "b"], indent=2) + "\n", encoding="utf-8")

            cmd = [
                _py(),
                "-m",
                "scalpel.tools.plan_ops",
                "--in",
                str(payload_path),
                "--selected",
                str(selected_path),
                "--op",
                "align-starts",
                "--overrides-out",
                str(overrides_path),
                "--snap",
                "10",
            ]
            p = subprocess.run(cmd, cwd=str(REPO_ROOT), text=True, capture_output=True)
            combined = (p.stdout or "") + "\n" + (p.stderr or "")
            self.assertEqual(p.returncode, 0, combined)

            out = json.loads(overrides_path.read_text(encoding="utf-8"))
            self.assertIn("a", out)
            self.assertIn("b", out)
            self.assertEqual(out["a"]["start_ms"], out["b"]["start_ms"])


if __name__ == "__main__":
    unittest.main(verbosity=2)
