#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Validation gates for swarm autopilot agents."""
from __future__ import annotations

import subprocess
import sys

from pulse.cli import ROOT_DIR


def _diff_snapshot() -> dict[str, tuple[int, int]]:
    """Capture current git diff numstat as {file: (added, removed)}."""
    snap: dict[str, tuple[int, int]] = {}
    try:
        r = subprocess.run(
            ["git", "diff", "--numstat"],
            capture_output=True, text=True, timeout=10, cwd=str(ROOT_DIR),
            encoding="utf-8", errors="replace",
        )
        for line in r.stdout.strip().splitlines():
            parts = line.split("	")
            if len(parts) >= 3:
                try:
                    snap[parts[2]] = (int(parts[0]), int(parts[1]))
                except ValueError:
                    pass
    except Exception:
        pass
    return snap


def _run_gates(max_diff_lines, pre_snapshot: dict[str, tuple[int, int]] | None = None):
    """Validate agent work. Only counts lines the AGENT changed (delta from pre_snapshot)."""
    gates_passed = True
    failures = []

    try:
        post_snapshot = _diff_snapshot()
        if pre_snapshot is not None:
            delta = 0
            for f in set(post_snapshot) | set(pre_snapshot):
                post_add, post_rm = post_snapshot.get(f, (0, 0))
                pre_add, pre_rm = pre_snapshot.get(f, (0, 0))
                delta += abs(post_add - pre_add) + abs(post_rm - pre_rm)
        else:
            delta = sum(a + r for a, r in post_snapshot.values())

        if delta > max_diff_lines:
            gates_passed = False
            failures.append(f"diff-guard: {delta} lines (max {max_diff_lines})")
        if delta == 0:
            untracked = subprocess.run(
                ["git", "ls-files", "--others", "--exclude-standard"],
                capture_output=True, text=True, cwd=str(ROOT_DIR),
                encoding="utf-8", errors="replace",
            ).stdout.strip()
            if not untracked:
                gates_passed = False
                failures.append("zero-work: 0 lines changed")
    except Exception:
        pass

    smoke = ROOT_DIR / "tests" / "smoke_test.py"
    if smoke.exists():
        try:
            r = subprocess.run(
                [sys.executable, str(smoke)],
                capture_output=True, text=True, timeout=30, cwd=str(ROOT_DIR),
                encoding="utf-8", errors="replace")
            if r.returncode != 0:
                gates_passed = False
                err_hint = (r.stderr or r.stdout or "")[:200].strip()
                failures.append(f"smoke-test failed: {err_hint}" if err_hint else "smoke-test failed")
        except Exception:
            pass

    return gates_passed, failures, post_snapshot
