"""CLI for error pattern learning management."""

import json
from typing import Optional

import click

from oclawma.learning import ErrorPatternStore, get_default_learner


@click.group(name="learning")
def learning_cli() -> None:
    """Error pattern learning and auto-correction commands."""
    pass


@learning_cli.command(name="status")
@click.option("--json-output", "-j", is_flag=True, help="Output as JSON")
def status(json_output: bool) -> None:
    """Show error pattern learning status."""
    learner = get_default_learner()
    stats = learner.get_learning_stats()

    if json_output:
        click.echo(json.dumps(stats, indent=2))
    else:
        click.echo("╔══════════════════════════════════════════════════════════╗")
        click.echo("║         ERROR PATTERN LEARNING STATUS                    ║")
        click.echo("╚══════════════════════════════════════════════════════════╝")
        click.echo()
        click.echo(f"📊 Total Patterns Tracked: {stats['total_patterns']}")
        click.echo(f"🔄 Recurring Patterns (7d): {stats['recurring_patterns']}")
        click.echo(f"⚠️  Total Errors (24h): {stats['total_errors_24h']}")
        click.echo(f"🤖 Auto-Correctable Patterns: {stats['auto_correctable_patterns']}")
        click.echo()

        if stats["top_patterns"]:
            click.echo("🔥 Top Recurring Patterns:")
            for p in stats["top_patterns"]:
                icon = (
                    "🔴" if p["severity"] == "high" else "🟡" if p["severity"] == "medium" else "🟢"
                )
                click.echo(f"  {icon} {p['name']}: {p['count']} occurrences")


@learning_cli.command(name="report")
def report() -> None:
    """Generate detailed error pattern report."""
    learner = get_default_learner()
    click.echo(learner.generate_report())


@learning_cli.command(name="patterns")
@click.option("--category", "-c", help="Filter by category")
@click.option("--min-occurrences", "-m", default=0, type=int, help="Minimum occurrences")
def patterns(category: Optional[str], min_occurrences: int) -> None:
    """List detected error patterns."""
    store = ErrorPatternStore()
    all_patterns = store.get_all_patterns()

    # Filter patterns
    filtered = all_patterns
    if category:
        filtered = [p for p in filtered if p.category == category]
    if min_occurrences > 0:
        counts = store.get_pattern_counts(days=30)
        filtered = [p for p in filtered if counts.get(p.name, 0) >= min_occurrences]

    # Sort by occurrences
    counts = store.get_pattern_counts(days=30)
    filtered.sort(key=lambda p: counts.get(p.name, 0), reverse=True)

    click.echo(f"Found {len(filtered)} patterns:\n")

    for p in filtered:
        count = counts.get(p.name, 0)
        icon = "🔴" if p.severity == "high" else "🟡" if p.severity == "medium" else "🟢"
        auto = "🤖" if p.auto_correct else " "
        click.echo(f"{icon}{auto} {p.name}")
        click.echo(f"   Category: {p.category} | Severity: {p.severity} | Count: {count}")
        click.echo(f"   💡 {p.suggestion}")
        click.echo()


@learning_cli.command(name="recent")
@click.option("--hours", "-h", default=24, type=int, help="Hours to look back")
@click.option("--tool", "-t", help="Filter by tool name")
def recent_errors(hours: int, tool: Optional[str]) -> None:
    """Show recent errors."""
    store = ErrorPatternStore()
    errors = store.get_recent_errors(hours=hours)

    if tool:
        errors = [e for e in errors if e.tool_name == tool]

    click.echo(f"Recent errors (last {hours}h):\n")

    for error in errors[:20]:  # Limit to 20
        status = "✅" if error.resolved else "❌"
        click.echo(f"{status} [{error.timestamp.strftime('%Y-%m-%d %H:%M')}] {error.tool_name}")
        click.echo(f"   Type: {error.error_type}")
        click.echo(f"   Message: {error.error_message[:100]}...")
        if error.suggestion_applied:
            click.echo(f"   💡 Applied: {error.suggestion_applied}")
        click.echo()


@learning_cli.command(name="stats")
def stats() -> None:
    """Show detailed learning statistics."""
    learner = get_default_learner()
    store = learner.store

    # Get pattern counts
    counts = store.get_pattern_counts(days=30)
    patterns = store.get_all_patterns()

    click.echo("╔══════════════════════════════════════════════════════════╗")
    click.echo("║         DETAILED STATISTICS                              ║")
    click.echo("╚══════════════════════════════════════════════════════════╝")
    click.echo()

    # Category breakdown
    by_category: dict = {}
    for p in patterns:
        cat = p.category
        if cat not in by_category:
            by_category[cat] = {"count": 0, "patterns": []}
        by_category[cat]["count"] += counts.get(p.name, 0)
        by_category[cat]["patterns"].append(p.name)

    click.echo("📁 By Category:")
    for cat, data in sorted(by_category.items(), key=lambda x: x[1]["count"], reverse=True):
        click.echo(f"   {cat}: {data['count']} errors ({len(data['patterns'])} patterns)")

    click.echo()

    # Severity breakdown
    by_severity: dict = {"high": 0, "medium": 0, "low": 0}
    for p in patterns:
        by_severity[p.severity] = by_severity.get(p.severity, 0) + counts.get(p.name, 0)

    click.echo("🔴 By Severity:")
    for sev, count in sorted(by_severity.items(), key=lambda x: x[1], reverse=True):
        if count > 0:
            icon = "🔴" if sev == "high" else "🟡" if sev == "medium" else "🟢"
            click.echo(f"   {icon} {sev}: {count} errors")

    click.echo()

    # Auto-correction stats
    click.echo("🤖 Auto-Correction:")
    auto_correctable = [p for p in patterns if p.auto_correct]
    click.echo(f"   Enabled patterns: {len(auto_correctable)}")

    total_success_rate = 0.0
    for p in auto_correctable:
        rate = store.get_correction_success_rate(p.name)
        total_success_rate += rate
        click.echo(f"   {p.name}: {rate*100:.1f}% success rate")

    if auto_correctable:
        avg_rate = total_success_rate / len(auto_correctable)
        click.echo(f"   Average: {avg_rate*100:.1f}%")


@learning_cli.command(name="reset")
@click.confirmation_option(prompt="Are you sure you want to reset all error data?")
def reset() -> None:
    """Reset all error pattern data."""
    store = ErrorPatternStore()
    db_path = store.db_path

    if db_path.exists():
        db_path.unlink()
        click.echo("✅ Error pattern database reset.")
    else:
        click.echo("No database found.")


@learning_cli.command(name="test-correct")
@click.argument("tool_name")
@click.argument("error_message")
@click.option("--param", "-p", multiple=True, help="Parameters as key=value")
def test_correct(tool_name: str, error_message: str, param: tuple) -> None:
    """Test error correction for a given error."""
    learner = get_default_learner()

    # Parse parameters
    params = {}
    for p in param:
        if "=" in p:
            key, value = p.split("=", 1)
            params[key] = value

    suggestion = learner.suggest_correction(tool_name, params, error_message)

    if suggestion:
        click.echo(f"Pattern detected: {suggestion['pattern']}")
        click.echo(f"Suggestion: {suggestion['suggestion']}")
        if suggestion["corrected_params"]:
            click.echo(f"Auto-correct: {suggestion['auto_apply']}")
            click.echo(f"Corrected params: {json.dumps(suggestion['corrected_params'], indent=2)}")
    else:
        click.echo("No correction suggestion available for this error.")


def register_commands(cli: click.Group) -> None:
    """Register learning commands with the main CLI."""
    cli.add_command(learning_cli)
