"""
Pre-push Git hook for Warden.

Runs full Warden analysis before pushing to remote.
"""

import subprocess
import sys
from pathlib import Path
from typing import List, Optional


class PrePushHook:
    """Pre-push hook that runs full Warden analysis before push."""

    HOOK_SCRIPT = """#!/usr/bin/env python3
\"\"\"
Warden pre-push hook.

This hook runs full Warden analysis before pushing to remote.
Auto-generated by Warden Infrastructure Module.
\"\"\"

import subprocess
import sys


def main() -> int:
    \"\"\"Run full Warden analysis before push.\"\"\"
    print("🛡️  Running Warden pre-push checks...")
    print("This may take a few moments...")

    # Run full Warden analysis
    cmd = [
        "warden",
        "analyze",
        ".",
        "--frame", "security",
        "--frame", "fuzz",
        "--frame", "property",
        "--ci",
    ]

    result = subprocess.run(cmd, capture_output=True, text=True, check=False)

    if result.returncode != 0:
        print("❌ Warden found issues:")
        print(result.stdout)
        print("\\nPush blocked. Fix issues or use 'git push --no-verify' to bypass.")
        return 1

    print("✓ Warden pre-push checks passed!")
    return 0


if __name__ == "__main__":
    sys.exit(main())
"""

    @staticmethod
    def generate_script() -> str:
        """
        Generate pre-push hook script content.

        Returns:
            Hook script as string
        """
        return PrePushHook.HOOK_SCRIPT

    @staticmethod
    def install(git_dir: Path, force: bool = False) -> bool:
        """
        Install pre-push hook.

        Args:
            git_dir: Path to .git directory
            force: Overwrite existing hook

        Returns:
            True if installed, False otherwise
        """
        hooks_dir = git_dir / "hooks"
        if not hooks_dir.exists():
            hooks_dir.mkdir(parents=True, exist_ok=True)

        hook_path = hooks_dir / "pre-push"

        if hook_path.exists() and not force:
            return False

        hook_path.write_text(PrePushHook.HOOK_SCRIPT)
        hook_path.chmod(0o755)  # Make executable

        return True

    @staticmethod
    def uninstall(git_dir: Path) -> bool:
        """
        Uninstall pre-push hook.

        Args:
            git_dir: Path to .git directory

        Returns:
            True if uninstalled, False otherwise
        """
        hook_path = git_dir / "hooks" / "pre-push"

        if not hook_path.exists():
            return False

        # Check if it's a Warden hook
        content = hook_path.read_text()
        if "Warden pre-push hook" not in content:
            return False  # Don't remove non-Warden hooks

        hook_path.unlink()
        return True

    @staticmethod
    def is_installed(git_dir: Path) -> bool:
        """
        Check if pre-push hook is installed.

        Args:
            git_dir: Path to .git directory

        Returns:
            True if installed, False otherwise
        """
        hook_path = git_dir / "hooks" / "pre-push"

        if not hook_path.exists():
            return False

        content = hook_path.read_text()
        return "Warden pre-push hook" in content

    @staticmethod
    def run() -> int:
        """
        Run pre-push hook logic.

        Returns:
            Exit code (0 = success, 1 = failure)
        """
        print("🛡️  Running Warden pre-push checks...")
        print("This may take a few moments...")

        cmd = [
            "warden",
            "analyze",
            ".",
            "--frame",
            "security",
            "--frame",
            "fuzz",
            "--frame",
            "property",
            "--ci",
        ]

        result = subprocess.run(cmd, capture_output=True, text=True, check=False)

        if result.returncode != 0:
            print("❌ Warden found issues:")
            print(result.stdout)
            print("\nPush blocked. Fix issues or use 'git push --no-verify' to bypass.")
            return 1

        print("✓ Warden pre-push checks passed!")
        return 0
