#!/usr/bin/env python3
"""
SWE Agent - Headless Agentic IDE
Main entry point for the Software Engineering Agent system with comprehensive tool support.
"""

import sys
import argparse
import logging
from pathlib import Path
from typing import Optional

# Add the project root to the path
sys.path.insert(0, str(Path(__file__).parent))

from cli.interface import SWEInterface
from cli.pair_programming_interface import PairProgrammingInterface
from cli.warp_interface import WarpInterface
from config.settings import Settings
from workflows.clean_swe_workflow import CleanSWEWorkflow
from rich.console import Console
from rich.panel import Panel
from rich.text import Text

console = Console()


def setup_logging(log_level: str = "INFO") -> None:
    """
    Setup logging configuration for the SWE Agent system.
    
    Args:
        log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
    """
    level = getattr(logging, log_level.upper())
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')


def create_parser() -> argparse.ArgumentParser:
    """
    Create command-line argument parser.
    
    Returns:
        Configured argument parser
    """
    parser = argparse.ArgumentParser(
        description=
        "SWE Agent - Headless Agentic IDE with comprehensive tool support",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
    %(prog)s --interactive                 # Start interactive mode
    %(prog)s --pair                        # Start pair programming interface (like Aider)
    %(prog)s --task "create a calculator"  # Execute specific task
    %(prog)s --help                        # Show this help message
    %(prog)s --status                      # Show current workflow status
        """)

    # Main operation modes
    parser.add_argument(
        "--interactive",
        action="store_true",
        help="Start interactive mode for continuous task input")

    parser.add_argument("--task", type=str, help="Execute a specific task")

    parser.add_argument("--status",
                        action="store_true",
                        help="Show current workflow status")

    # Configuration options
    parser.add_argument(
        "--repo-path",
        type=str,
        default=".",
        help="Path to the repository to analyze (default: current directory)")

    parser.add_argument("--output-dir",
                        type=str,
                        default="output",
                        help="Output directory for results (default: output)")

    parser.add_argument("--log-level",
                        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
                        default="INFO",
                        help="Set logging level (default: INFO)")
    
    parser.add_argument(
        "--use-planner",
        action="store_true",
        help="Enable planner agent for complex task planning (default: disabled)")
    
    parser.add_argument("--pair", action="store_true",
                       help="Start pair programming interface (interactive with enhanced UI)")
    
    parser.add_argument("--warp", action="store_true",
                       help="Start Warp-style AI terminal interface")

    return parser


def run_interactive_mode(settings: Settings) -> int:
    """
    Run the SWE Agent in interactive mode.
    
    Args:
        settings: Application settings
        
    Returns:
        Exit code
    """
    try:
        interface = SWEInterface(settings)
        interface.start_interactive_mode()
        return 0
    except KeyboardInterrupt:
        console.print(
            "\n[yellow]Interactive mode interrupted by user[/yellow]")
        return 0
    except Exception as e:
        console.print(f"[red]Error in interactive mode: {e}[/red]")
        return 1


def run_single_task(task: str, settings: Settings) -> int:
    """
    Run a single task using the SWE Agent.
    
    Args:
        task: Task description
        settings: Application settings
        
    Returns:
        Exit code
    """
    try:
        console.print(
            Panel(Text(f"Executing Task: {task}", style="bold blue"),
                  title="SWE Agent",
                  border_style="blue"))

        workflow = CleanSWEWorkflow(settings.repo_path, settings.output_dir, settings.use_planner)
        result = workflow.run_workflow(task)

        console.print(
            Panel(Text("Task completed successfully", style="bold green"),
                  title="Result",
                  border_style="green"))

        return 0
    except Exception as e:
        console.print(f"[red]Error executing task: {e}[/red]")
        return 1


def show_status(settings: Settings) -> int:
    """
    Show current workflow status.
    
    Args:
        settings: Application settings
        
    Returns:
        Exit code
    """
    try:
        workflow = CleanSWEWorkflow(settings.repo_path, settings.output_dir, settings.use_planner)
        # Clean workflow doesn't have get_workflow_status method, so just show basic info
        status = f"Clean workflow initialized (Planner: {'enabled' if settings.use_planner else 'disabled'})"

        console.print(
            Panel(Text(f"Repository: {settings.repo_path}\nStatus: {status}",
                       style="bold cyan"),
                  title="SWE Agent Status",
                  border_style="cyan"))

        return 0
    except Exception as e:
        console.print(f"[red]Error getting status: {e}[/red]")
        return 1


def main() -> int:
    """
    Main entry point for the SWE Agent system.
    
    Returns:
        Exit code
    """
    parser = create_parser()
    args = parser.parse_args()

    # Setup logging
    setup_logging(args.log_level)

    # Create settings
    settings = Settings(repo_path=Path(args.repo_path),
                        output_dir=Path(args.output_dir),
                        use_planner=args.use_planner)

    # Validate repository path
    if not settings.repo_path.exists():
        console.print(
            f"[red]Error: Repository path '{settings.repo_path}' does not exist[/red]"
        )
        return 1

    # Execute based on arguments
    if args.pair:
        # Start pair programming interface
        pair_interface = PairProgrammingInterface(
            repo_path=str(settings.repo_path),
            output_dir=str(settings.output_dir)
        )
        pair_interface.run()
        return 0
    elif args.warp:
        # Start Warp-style AI terminal interface
        import asyncio
        warp_interface = WarpInterface(
            repo_path=str(settings.repo_path),
            output_dir=str(settings.output_dir)
        )
        asyncio.run(warp_interface.run())
        return 0
    elif args.interactive:
        return run_interactive_mode(settings)
    elif args.task:
        return run_single_task(args.task, settings)
    elif args.status:
        return show_status(settings)
    else:
        # Default to interactive mode if no specific action is specified
        return run_interactive_mode(settings)


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