"""
Command Line Interface for the Alloy Programming Language

This module provides the main CLI entry point for both interactive REPL
and file execution modes.
"""

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

from .interpreter import Interpreter
from .parser import AlloyParser
from .repl import AlloyREPL


def main():
    """Main CLI entry point"""
    parser = argparse.ArgumentParser(
        description="Alloy Programming Language Interpreter",
        prog="alloy"
    )
    
    parser.add_argument(
        "file", 
        nargs="?", 
        help="Alloy source file (.ay) to execute"
    )
    
    parser.add_argument(
        "--version", 
        action="version", 
        version="%(prog)s 0.1.0"
    )
    
    parser.add_argument(
        "--debug", 
        action="store_true", 
        help="Enable debug output"
    )
    
    parser.add_argument(
        "--model",
        default="gpt-4o-mini",
        help="Default AI model to use (default: gpt-4o-mini)"
    )

    args = parser.parse_args()
    
    if args.file:
        # File execution mode
        execute_file(args.file, args.debug, args.model)
    else:
        # Interactive REPL mode
        start_repl(args.debug, args.model)


def execute_file(file_path: str, debug: bool = False, model: str = "gpt-4o-mini"):
    """Execute an Alloy source file"""
    path = Path(file_path)
    
    # Check file extension
    if not path.suffix == ".ay":
        print(f"Error: File must have .ay extension, got: {path.suffix}")
        sys.exit(1)
    
    # Check if file exists
    if not path.exists():
        print(f"Error: File not found: {file_path}")
        sys.exit(1)
    
    try:
        # Read the source code
        with open(path, 'r', encoding='utf-8') as f:
            source_code = f.read()
        
        # Create parser and interpreter
        parser = AlloyParser()
        interpreter = Interpreter(use_gpt4_mini=(model == "gpt-4o-mini"))
        
        if debug:
            print(f"Executing: {file_path}")
            print(f"Model: {model}")
            print("-" * 40)
        
        # Parse and execute
        ast = parser.parse(source_code, debug=debug)
        result = interpreter.interpret(ast)
        
        # Only print result if it's not None
        if result is not None:
            print(result)
            
    except FileNotFoundError:
        print(f"Error: File not found: {file_path}")
        sys.exit(1)
    except Exception as e:
        print(f"Error executing {file_path}: {e}")
        if debug:
            import traceback
            traceback.print_exc()
        sys.exit(1)


def start_repl(debug: bool = False, model: str = "gpt-4o-mini"):
    """Start the interactive REPL"""
    repl = AlloyREPL(debug=debug, model=model)
    repl.run()


if __name__ == "__main__":
    main()