"""
Example script showing how to use Bolor programmatically.

This script demonstrates how to use Bolor to scan and fix issues in code
without using the command-line interface.
"""

import sys
from pathlib import Path
from rich.console import Console

# Add the parent directory to the path to import bolor
sys.path.insert(0, str(Path(__file__).parent.parent))

from bolor.utils.config import Config
from bolor.agent.scanner import Scanner
from bolor.agent.fixer import Fixer
from bolor.agent.planner import Planner


def main():
    """
    Main function demonstrating Bolor's API usage.
    """
    console = Console()
    console.print("[bold blue]Bolor Programmatic API Example[/bold blue]")
    
    # Create a configuration
    config = Config()
    config.set("verbose", True)
    
    # Target file to scan and fix
    file_path = Path(__file__).parent / "buggy_code.py"
    console.print(f"\n[bold green]Target file:[/bold green] {file_path}")
    
    # Example 1: Scanning for issues
    console.print("\n[bold magenta]Example 1: Scanning for issues[/bold magenta]")
    scanner = Scanner(config)
    issues = scanner.scan_file(file_path)
    
    console.print(f"Found [bold]{len(issues)}[/bold] issues:")
    for i, issue in enumerate(issues, 1):
        console.print(f"  [bold cyan]Issue {i}:[/bold cyan] {issue.issue_type.value}")
        console.print(f"  [dim]Description:[/dim] {issue.description}")
        console.print(f"  [dim]Location:[/dim] Line {issue.line_number}")
        if issue.code_snippet:
            console.print(f"  [dim]Code:[/dim] {issue.code_snippet.strip()}")
        console.print()
    
    # Example 2: Fixing issues (without saving changes)
    console.print("\n[bold magenta]Example 2: Generating fixes (without saving)[/bold magenta]")
    fixer = Fixer(config)
    
    # For demonstration purpose, we'll just fix the first issue
    # In a real scenario, you might want to fix all issues
    if issues:
        first_issue = issues[0]
        
        # Create a copy of the issue to avoid modifying the original
        import copy
        issue_copy = copy.deepcopy(first_issue)
        
        # For demonstration, we're not actually saving the changes
        # The fixer would normally modify the file, but we're just generating a fix
        with open(file_path, 'r', encoding='utf-8') as f:
            file_content = f.read()
        
        # Initialize the LLM (note: this would normally download models in a real scenario)
        # For demo purposes, we'll skip the actual LLM generation
        console.print("[yellow]Note: Skipping actual LLM initialization for this demo[/yellow]")
        
        # Simulate a fix being generated
        if issue_copy.issue_type.value == "syntax_error" and "Missing colon" in issue_copy.description:
            fixed_code = "def calculate_average(numbers):\n    total = sum(numbers)\n    count = len(numbers)\n    return total / count"
            issue_copy.fixed_code_snippet = fixed_code
            issue_copy.confidence_score = 0.95
            
            console.print(f"[bold green]Generated fix for issue:[/bold green] {issue_copy.description}")
            console.print(f"[dim]Original code:[/dim]\n{issue_copy.code_snippet}")
            console.print(f"[dim]Fixed code:[/dim]\n{issue_copy.fixed_code_snippet}")
            console.print(f"[dim]Confidence score:[/dim] {issue_copy.confidence_score}")
    
    # Example 3: Planning improvements
    console.print("\n[bold magenta]Example 3: Planning improvements[/bold magenta]")
    planner = Planner(config)
    
    # For demonstration purpose, we'll create mock suggestions
    # In a real scenario, these would be generated by analyzing the code
    console.print("[yellow]Note: Creating mock suggestions for this demo[/yellow]")
    
    suggestions = [
        {
            "title": "Improve function naming",
            "description": "Function 'x' has a non-descriptive name. Consider renaming it to 'add' or 'sum' to better reflect its purpose.",
            "file": str(file_path),
            "line": 35,
        },
        {
            "title": "Add docstrings",
            "description": "Function 'calculate_tax' is missing a docstring. Consider adding a docstring to document the function's purpose and parameters.",
            "file": str(file_path),
            "line": 39,
        },
        {
            "title": "Fix security vulnerability",
            "description": "Using 'shell=True' with subprocess.call() is a security vulnerability. Consider using subprocess.run() with a list of arguments instead.",
            "file": str(file_path),
            "line": 31,
        }
    ]
    
    console.print(f"Generated [bold]{len(suggestions)}[/bold] improvement suggestions:")
    for i, suggestion in enumerate(suggestions, 1):
        console.print(f"  [bold cyan]Suggestion {i}:[/bold cyan] {suggestion['title']}")
        console.print(f"  [dim]Description:[/dim] {suggestion['description']}")
        console.print(f"  [dim]Location:[/dim] {suggestion['file']}:{suggestion['line']}")
        console.print()
    
    console.print("\n[bold blue]End of Bolor API demonstration[/bold blue]")


if __name__ == "__main__":
    main()
