"""Core GuardRail processing logic."""

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

import click

from guardrail.config import GuardRailConfig
from guardrail.cli.detection import detect_and_analyze_changes
from guardrail.cli.test_generation import (
    generate_tests_for_functions,
    print_test_generation_summary,
)
from guardrail.cli.test_execution import run_and_report_tests


def run_guardrail_checks(
    root: Optional[Path], execute_command: bool = True, command: Optional[tuple] = None
) -> bool:
    """
    Run GuardRail checks (detection, classification, test generation, execution).
    
    Args:
        root: Project root directory.
        execute_command: Whether to execute the user command at the end.
        command: Command to execute if execute_command is True.
    
    Returns:
        True if checks passed (or no tests), False if tests failed.
    """
    config = GuardRailConfig(root=root)
    
    if not config.ensure_initialized():
        click.echo("❌ GuardRail not initialized. Run 'guardrail init' first.", err=True)
        sys.exit(1)

    # Detect and analyze changed functions
    changed_files, pure_functions, side_effect_functions, function_to_file = (
        detect_and_analyze_changes(config.root)
    )

    # Generate and run tests for pure functions
    if pure_functions:
        generated_tests, cached_tests, function_test_map = generate_tests_for_functions(
            config, pure_functions, function_to_file
        )

        if generated_tests:
            print_test_generation_summary(
                generated_tests, cached_tests, config.get_test_dir(), config.root
            )

            success = run_and_report_tests(
                config.get_test_dir(),
                config.root,
                function_test_map,
                execute_command,
                function_to_file=function_to_file,
            )
            if not success:
                return False

    # Execute user command if requested
    if execute_command and command:
        execute_user_command(command)

    return True


def execute_user_command(command: tuple) -> None:
    """Execute the user's command."""
    click.echo(f"\n🚀 Running: {' '.join(command)}")

    try:
        result = subprocess.run(command, check=False)
        sys.exit(result.returncode)
    except KeyboardInterrupt:
        click.echo("\n⚠️  Command interrupted by user", err=True)
        sys.exit(130)
    except Exception as e:
        click.echo(f"❌ Error running command: {e}", err=True)
        sys.exit(1)

