#!/usr/bin/env python3
"""Read-only OpenTofu state lock and drift inspection."""

from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from cluster_runtime_context import environment

os.environ.update(environment())

STACKS = {
    "provisioning": "bootstrap/provisioning",
    "cluster": "bootstrap/cluster",
    "platform": "bootstrap/platform",
    "apps": "bootstrap/apps",
    "edge": "bootstrap/edge",
    "oci": "bootstrap/oci",
}


def inspect_stack(repo: Path, name: str, relative: str) -> dict:
    directory = repo / relative
    row = {"stack": name, "path": relative, "state": "missing", "lock": "clear", "drift": "unknown"}
    state_file = directory / "terraform.tfstate"
    if name in {"cluster", "platform", "apps"} or relative in {"bootstrap/cluster", "bootstrap/platform", "bootstrap/apps"}:
        context = json.loads(subprocess.check_output(
            [sys.executable, str(repo / "scripts/cluster-context.py"), "status"], text=True,
        ))
        state_file = Path(context["states"][directory.name])
    if relative == "bootstrap/oci" and os.environ.get("LAB_OCI_FOUNDATION_STATE_FILE"):
        state_file = Path(os.environ["LAB_OCI_FOUNDATION_STATE_FILE"]).expanduser()
    row["state_path"] = str(state_file)
    lock_file = state_file.with_name("." + state_file.name + ".lock.info")
    if not state_file.exists():
        row["detail"] = "local state file not found"
        return row
    row["state"] = "present"
    if lock_file.exists():
        row["lock"] = "locked"
        try:
            info = json.loads(lock_file.read_text())
            row["lock_info"] = {key: info.get(key) for key in ("ID", "Operation", "Who", "Version", "Created", "Path") if info.get(key)}
        except (OSError, json.JSONDecodeError):
            row["lock_info"] = {"detail": "lock metadata is not valid JSON"}

    command = [
        sys.executable,
        str(repo / "scripts/cluster-context.py"), "tool", "tofu",
        f"-chdir={directory}",
        "plan",
        "-input=false",
        "-no-color",
        "-refresh-only",
        "-detailed-exitcode",
        "-lock-timeout=0s",
    ]
    if relative == "bootstrap/oci":
        command.append(f"-state={state_file}")
    try:
        completed = subprocess.run(command, text=True, capture_output=True, timeout=900)
        output = (completed.stdout + "\n" + completed.stderr).strip()
    except FileNotFoundError:
        row.update(drift="unknown", detail="tofu is not installed")
        return row
    except subprocess.TimeoutExpired:
        row.update(drift="unknown", detail="refresh-only plan timed out")
        return row

    tail = [line.strip() for line in output.splitlines() if line.strip()][-6:]
    lock_error = re.search(r"state lock|Error acquiring the state lock|already locked", output, re.IGNORECASE)
    if lock_error:
        row["lock"] = "locked"
        row["drift"] = "unknown"
        row["detail"] = "state lock prevented inspection"
    elif completed.returncode == 0:
        row["drift"] = "clean"
        row["detail"] = tail[-1] if tail else "refresh-only plan clean"
    elif completed.returncode == 2:
        row["drift"] = "detected"
        row["detail"] = " | ".join(tail[-3:])
    else:
        row["drift"] = "unknown"
        row["detail"] = " | ".join(tail[-3:]) or "refresh-only plan failed"
    return row


def main() -> int:
    parser = argparse.ArgumentParser(description="Inspect OpenTofu state locks and drift without changing state")
    parser.add_argument("stack", nargs="?", help="provisioning, cluster, platform, apps, edge, oci, or bootstrap path")
    parser.add_argument("--json", action="store_true", dest="as_json")
    args = parser.parse_args()
    if args.stack and args.stack not in STACKS and args.stack not in STACKS.values():
        parser.error(f"unknown stack {args.stack!r}; use {', '.join(STACKS)}")
    selected = [(args.stack, args.stack)] if args.stack in STACKS.values() else [(args.stack or key, value) for key, value in STACKS.items() if not args.stack or key == args.stack]
    repo = Path(__file__).resolve().parents[1]
    rows = [inspect_stack(repo, name, path) for name, path in selected]
    failures = [item for item in rows if item["lock"] == "locked" or item["drift"] in ("detected", "unknown")]
    report = {"title": "OpenTofu State Status", "status": "warn" if failures else "pass", "rows": rows}
    if args.as_json:
        print(json.dumps(report, indent=2))
    else:
        print("== OpenTofu State Status ==")
        for item in rows:
            print(f"{item['stack']}: state={item['state']} lock={item['lock']} drift={item['drift']}")
            if item.get("detail"):
                print(f"  detail: {item['detail']}")
            if item.get("lock_info"):
                print(f"  lock: {json.dumps(item['lock_info'], sort_keys=True)}")
        print(f"Overall: {report['status']}")
    return 1 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main())
