import json
import subprocess


def load_terraform_plan(var_file=None):

    try:

        # Build terraform plan command
        cmd = ["terraform", "plan", "-out", "tfplan"]

        if var_file:
            cmd.append(f"-var-file={var_file}")
        print("Running terraform plan...")
        # Run terraform plan
        subprocess.run(
            cmd,
            check=True,
            capture_output=True,
            text=True
        )

        # Get terraform JSON output
        result = subprocess.run(
            ["terraform", "show", "-json", "tfplan"],
            check=True,
            capture_output=True,
            text=True
        )

        return json.loads(result.stdout)

    except subprocess.CalledProcessError as e:
        raise Exception("Terraform execution failed:\n" + e.stderr)


def parse_plan(var_file=None):

    # Load Terraform plan
    plan = load_terraform_plan(var_file)

    resources = []
    region = None

    for r in plan.get("resource_changes", []):

        change = r.get("change", {})
        actions = change.get("actions", [])

        before = change.get("before")
        after = change.get("after")

        # Use after for create/update, before for delete
        config = after if after is not None else before

        if config is None:
            continue

        # Detect region
        if not region and isinstance(config, dict) and "region" in config:
            region = config["region"]

        resource = {
            "type": r.get("type"),
            "address": r.get("address"),
            "config": after,
            "before": before,
            "actions": actions
        }

        resources.append(resource)

    # Fallback region
    if not region:
        region = "us-east-1"

    return resources, region