"""Tests for the abi-spec CLI."""
import subprocess
import sys
from pathlib import Path

FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"


class TestCLICompile:
    def test_compile_success(self, tmp_path):
        out = tmp_path / "out"
        result = subprocess.run(
            [sys.executable, "-m", "abi_spec", "compile", str(FIXTURES / "prd.json"),
             "--out", str(out)],
            capture_output=True,
            text=True,
        )
        assert result.returncode == 0
        assert "manifest_hash:" in result.stdout
        assert "prd_hash:" in result.stdout

    def test_compile_bad_input(self, tmp_path):
        bad = tmp_path / "bad.json"
        bad.write_text("{}", encoding="utf-8")
        result = subprocess.run(
            [sys.executable, "-m", "abi_spec", "compile", str(bad),
             "--out", str(tmp_path / "out")],
            capture_output=True,
            text=True,
        )
        assert result.returncode == 1


class TestCLIValidate:
    def test_validate_success(self, tmp_path):
        out = tmp_path / "out"
        # First compile
        subprocess.run(
            [sys.executable, "-m", "abi_spec", "compile", str(FIXTURES / "prd.json"),
             "--out", str(out)],
            capture_output=True,
        )
        # Then validate
        result = subprocess.run(
            [sys.executable, "-m", "abi_spec", "validate", str(out)],
            capture_output=True,
            text=True,
        )
        assert result.returncode == 0
        assert "PASS" in result.stdout

    def test_validate_missing_dir(self, tmp_path):
        result = subprocess.run(
            [sys.executable, "-m", "abi_spec", "validate", str(tmp_path / "nonexistent")],
            capture_output=True,
            text=True,
        )
        assert result.returncode == 1


class TestCLINoCommand:
    def test_no_command_shows_help(self):
        result = subprocess.run(
            [sys.executable, "-m", "abi_spec"],
            capture_output=True,
            text=True,
        )
        assert result.returncode == 1
