"""
RLM Commands for Large Codebases

Simple commands that leverage RLM's unlimited context.
"""

import sys
from pathlib import Path
from typing import Optional

import click
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel

from groknroll.core.rlm_codebase import RLMCodebaseAnalyzer

console = Console()


@click.group()
def rlm():
    """RLM-powered commands for unlimited context (large codebases)"""
    pass


@rlm.command()
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--focus", help="Focus area (security, architecture, performance)")
@click.option("--max-cost", type=float, default=10.0, help="Max cost in dollars")
def analyze_all(path: Optional[str], focus: Optional[str], max_cost: float):
    """
    Analyze ENTIRE codebase with RLM (unlimited context!)

    RLM will recursively explore your entire project.
    No context limits. No chunking needed.
    """
    project_path = Path(path) if path else Path.cwd()

    try:
        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]Analyzing entire codebase with RLM[/bold cyan]\n\n"
                f"[yellow]Note:[/yellow] RLM has unlimited context!\n"
                f"It will recursively explore ALL files as needed.\n\n"
                f"[dim]Max cost: ${max_cost}[/dim]",
                title="[bold]RLM Analysis[/bold]",
                border_style="cyan",
            )
        )

        with console.status("[bold cyan]RLM exploring codebase..."):
            analyzer = RLMCodebaseAnalyzer(project_path, max_cost=max_cost)

            console.print(f"\n[dim]Project: {analyzer.context.project_path.name}[/dim]")
            console.print(f"[dim]Files: {analyzer.context.total_files:,}[/dim]")
            console.print(f"[dim]Lines: {analyzer.context.total_lines:,}[/dim]\n")

            result = analyzer.analyze_entire_codebase(focus=focus)

        # Display results
        console.print()
        console.print(
            Panel(
                Markdown(result),
                title="[bold green]✓ RLM Analysis Complete[/bold green]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        import traceback

        traceback.print_exc()
        sys.exit(1)


@rlm.command()
@click.argument("issue")
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--max-cost", type=float, default=5.0, help="Max cost in dollars")
def fix(issue: str, path: Optional[str], max_cost: float):
    """
    Find and fix issue across ENTIRE codebase

    RLM will search through all files to find and fix the issue.
    """
    project_path = Path(path) if path else Path.cwd()

    try:
        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]RLM will find and fix:[/bold cyan]\n{issue}\n\n"
                f"[yellow]Searching entire codebase...[/yellow]",
                title="[bold]Find & Fix[/bold]",
                border_style="cyan",
            )
        )

        with console.status("[bold cyan]RLM working..."):
            analyzer = RLMCodebaseAnalyzer(project_path, max_cost=max_cost)
            result = analyzer.find_and_fix(issue)

        console.print()
        console.print(
            Panel(
                Markdown(result),
                title="[bold green]✓ Fix Complete[/bold green]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@rlm.command()
@click.argument("feature")
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--max-cost", type=float, default=10.0, help="Max cost in dollars")
def implement(feature: str, path: Optional[str], max_cost: float):
    """
    Implement feature across ENTIRE codebase

    RLM understands the full architecture and implements consistently.
    """
    project_path = Path(path) if path else Path.cwd()

    try:
        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]RLM will implement:[/bold cyan]\n{feature}\n\n"
                f"[yellow]Analyzing architecture first...[/yellow]",
                title="[bold]Feature Implementation[/bold]",
                border_style="cyan",
            )
        )

        with console.status("[bold cyan]RLM implementing..."):
            analyzer = RLMCodebaseAnalyzer(project_path, max_cost=max_cost)
            result = analyzer.implement_feature(feature)

        console.print()
        console.print(
            Panel(
                Markdown(result),
                title="[bold green]✓ Implementation Complete[/bold green]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@rlm.command()
@click.argument("refactoring")
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--max-cost", type=float, default=10.0, help="Max cost in dollars")
def refactor(refactoring: str, path: Optional[str], max_cost: float):
    """
    Refactor across ENTIRE codebase

    RLM will find and refactor all matching code consistently.
    """
    project_path = Path(path) if path else Path.cwd()

    try:
        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]RLM will refactor:[/bold cyan]\n{refactoring}\n\n"
                f"[yellow]Finding all affected code...[/yellow]",
                title="[bold]Refactoring[/bold]",
                border_style="cyan",
            )
        )

        with console.status("[bold cyan]RLM refactoring..."):
            analyzer = RLMCodebaseAnalyzer(project_path, max_cost=max_cost)
            result = analyzer.refactor(refactoring)

        console.print()
        console.print(
            Panel(
                Markdown(result),
                title="[bold green]✓ Refactoring Complete[/bold green]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@rlm.command()
@click.argument("question")
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option("--max-cost", type=float, default=3.0, help="Max cost in dollars")
def ask(question: str, path: Optional[str], max_cost: float):
    """
    Ask question about ENTIRE codebase

    RLM will explore files to find the answer.
    """
    project_path = Path(path) if path else Path.cwd()

    try:
        with console.status("[bold cyan]RLM searching for answer..."):
            analyzer = RLMCodebaseAnalyzer(project_path, max_cost=max_cost)
            result = analyzer.answer_question(question)

        console.print()
        console.print(
            Panel(
                Markdown(result), title=f"[bold cyan]Q: {question}[/bold cyan]", border_style="cyan"
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


@rlm.command()
@click.option("--path", type=click.Path(exists=True), help="Project path")
@click.option(
    "--type",
    "doc_type",
    default="overview",
    type=click.Choice(["overview", "api", "architecture"]),
    help="Documentation type",
)
@click.option("--max-cost", type=float, default=5.0, help="Max cost in dollars")
def document(path: Optional[str], doc_type: str, max_cost: float):
    """
    Generate documentation for ENTIRE codebase

    RLM will explore and document the full project.
    """
    project_path = Path(path) if path else Path.cwd()

    try:
        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]Generating {doc_type} documentation[/bold cyan]\n\n"
                f"[yellow]RLM will explore entire codebase...[/yellow]",
                title="[bold]Documentation[/bold]",
                border_style="cyan",
            )
        )

        with console.status("[bold cyan]RLM generating docs..."):
            analyzer = RLMCodebaseAnalyzer(project_path, max_cost=max_cost)
            result = analyzer.generate_documentation(doc_type)

        console.print()
        console.print(
            Panel(
                Markdown(result),
                title=f"[bold green]✓ {doc_type.title()} Documentation[/bold green]",
                border_style="green",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")
        sys.exit(1)


if __name__ == "__main__":
    rlm()
