import json
import os
import subprocess
import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parent.parent


class TestPipelineIntegration:
    def test_load_stack_and_adapt_offline(self, tmp_path):
        stack = json.load(open(ROOT / "modules/l1/s3/instance.json"))
        assert stack["stack"]["name"] == "s3"

        sys.path.insert(0, str(ROOT))
        from adapters.terraform.adapter import adapt
        out_dir = str(tmp_path / "tf")
        adapt(stack, out_dir)

        assert os.path.isfile(os.path.join(out_dir, "main.tf"))
        assert os.path.isfile(os.path.join(out_dir, "terraform.tf"))
        assert os.path.isfile(os.path.join(out_dir, "providers.tf"))

        main_tf = open(os.path.join(out_dir, "main.tf")).read()
        assert 'module "s3"' in main_tf
        assert "acdl-spike-bucket" in main_tf

    def test_confidence_signal_with_adapted_tf(self):
        sys.path.insert(0, str(ROOT))
        from core.confidence_signal import compute

        inputs = {
            "policy": [{"result": "pass"}],
            "validation": {"schema": True, "stack_resolved": True,
                           "tf_validated": True, "tf_planned": True},
            "freshness": {"age_days": 0, "max_age_days": 7},
            "source": {"submitter": "test", "commit_sha": "test-sha"},
            "history": {"prior_rollbacks": 0, "prior_policy_fails": 0},
            "nfrs": {"conformance": None},
        }
        sig = compute("integration-test", "dev", inputs)
        assert sig.band == "pass"
        assert sig.score >= 0.50

    def test_run_platform_check_only(self):
        result = subprocess.run(
            ["bash", str(ROOT / "scripts/run_platform.sh"), "--check-only"],
            capture_output=True, text=True, cwd=str(ROOT),
            timeout=30,
        )
        assert result.returncode == 0, f"stdout: {result.stdout}\nstderr: {result.stderr}"
        assert "PLATFORM CHECK OK" in result.stdout

    def test_run_platform_check_only_no_aws_creds(self):
        env = os.environ.copy()
        env.pop("AWS_ACCESS_KEY_ID", None)
        env.pop("AWS_SECRET_ACCESS_KEY", None)
        env.pop("AWS_DEFAULT_REGION", None)
        result = subprocess.run(
            ["bash", str(ROOT / "scripts/run_platform.sh"), "--check-only"],
            capture_output=True, text=True, cwd=str(ROOT), env=env,
            timeout=30,
        )
        assert result.returncode == 0
        assert "PLATFORM CHECK OK" in result.stdout

    def test_run_platform_apply_mode_parses(self):
        """--apply mode parses without 'unknown flag' error (requires a contract)."""
        result = subprocess.run(
            ["bash", str(ROOT / "scripts/run_platform.sh"), "--apply"],
            capture_output=True, text=True, cwd=str(ROOT),
            timeout=10,
        )
        assert "unknown flag" not in result.stderr
        assert "contract file required" in result.stderr or result.returncode != 0

    def test_run_platform_destroy_mode_parses(self):
        """--destroy mode parses without 'unknown flag' error (requires a contract)."""
        result = subprocess.run(
            ["bash", str(ROOT / "scripts/run_platform.sh"), "--destroy"],
            capture_output=True, text=True, cwd=str(ROOT),
            timeout=10,
        )
        assert "unknown flag" not in result.stderr
        assert "contract file required" in result.stderr or result.returncode != 0

    def test_no_python_runs_terraform_apply_or_destroy(self):
        """D-101: Python scripts never run terraform apply or terraform destroy."""
        scripts_dir = ROOT / "scripts"
        for py_file in scripts_dir.glob("*.py"):
            content = py_file.read_text()
            assert "terraform apply" not in content, f"{py_file.name} contains 'terraform apply'"
            assert "terraform destroy" not in content, f"{py_file.name} contains 'terraform destroy'"