"""CLI for Self-Improvement Tools."""

from __future__ import annotations

import click

from oclawma.self_improvement.context_monitor import ContextMonitor
from oclawma.self_improvement.decision_audit_logger import DecisionAuditLogger
from oclawma.self_improvement.error_pattern_detector import ErrorPatternDetector
from oclawma.self_improvement.feedback_loop_closer import FeedbackLoopCloser
from oclawma.self_improvement.resource_tracker import ResourceTracker


@click.group(name="self-improvement")
def self_improvement_cli():
    """Self-improvement tools for monitoring and optimization."""
    pass


# Error Pattern Detector Commands
@self_improvement_cli.group(name="errors")
def errors_cli():
    """Error pattern detection and analysis."""
    pass


@errors_cli.command(name="analyze")
def errors_analyze():
    """Analyze logs for error patterns."""
    detector = ErrorPatternDetector()
    detector.analyze()


@errors_cli.command(name="report")
def errors_report():
    """Generate error pattern report."""
    detector = ErrorPatternDetector()
    detector.generate_report()


@errors_cli.command(name="suggest")
def errors_suggest():
    """Suggest rules based on error patterns."""
    detector = ErrorPatternDetector()
    detector.suggest_rules()


@errors_cli.command(name="apply-rules")
def errors_apply_rules():
    """Apply suggested rules to AGENTS.md."""
    detector = ErrorPatternDetector()
    detector.apply_rules()


# Feedback Loop Commands
@self_improvement_cli.group(name="feedback")
def feedback_cli():
    """Feedback loop for learning from corrections."""
    pass


@feedback_cli.command(name="list")
def feedback_list():
    """List pending corrections."""
    closer = FeedbackLoopCloser()
    closer.list_pending()


@feedback_cli.command(name="apply")
@click.argument("correction_id")
def feedback_apply(correction_id: str):
    """Apply a specific correction."""
    closer = FeedbackLoopCloser()
    closer.apply_correction(correction_id)


@feedback_cli.command(name="apply-all")
def feedback_apply_all():
    """Apply all pending corrections."""
    closer = FeedbackLoopCloser()
    closer.apply_all()


@feedback_cli.command(name="reject")
@click.argument("correction_id")
def feedback_reject(correction_id: str):
    """Reject a correction."""
    closer = FeedbackLoopCloser()
    closer.reject_correction(correction_id)


@feedback_cli.command(name="test")
@click.argument("message")
def feedback_test(message: str):
    """Test a message for correction detection."""
    closer = FeedbackLoopCloser()
    closer.test_message(message)


@feedback_cli.command(name="queue")
@click.argument("message")
def feedback_queue(message: str):
    """Manually queue a correction."""
    closer = FeedbackLoopCloser()
    result = closer.queue_correction(message)
    if result:
        click.echo(f"✅ Queued correction: {result['id']}")
    else:
        click.echo("❌ No correction pattern detected")


# Context Monitor Commands
@self_improvement_cli.group(name="context")
def context_cli():
    """Context window monitoring."""
    pass


@context_cli.command(name="check")
@click.argument("tokens", type=int, default=50000)
def context_check(tokens: int):
    """Check context status."""
    monitor = ContextMonitor()
    result = monitor.check_context(tokens)
    click.echo(result.message or f"✅ Context healthy: {result.percent}%")
    if result.actions:
        click.echo("\nRecommended actions:")
        for action in result.actions:
            click.echo(f"  • {action}")


@context_cli.command(name="history")
def context_history():
    """Show context usage history."""
    monitor = ContextMonitor()
    monitor.print_history()


@context_cli.command(name="estimate")
@click.argument("text", required=False)
def context_estimate(text: str | None):
    """Estimate token count for text."""
    monitor = ContextMonitor()
    if text is None:
        import sys

        text = sys.stdin.read()
    tokens = monitor.estimate_tokens(text)
    click.echo(f"Estimated tokens: {tokens:,}")


# Resource Tracker Commands
@self_improvement_cli.group(name="resources")
def resources_cli():
    """Resource usage tracking."""
    pass


@resources_cli.command(name="log")
@click.argument("op_type", default="operation")
@click.argument("cost", type=float, default=0.0)
@click.argument("description", nargs=-1)
def resources_log(op_type: str, cost: float, description: tuple):
    """Log an operation."""
    tracker = ResourceTracker()
    desc = " ".join(description) if description else "Unnamed operation"
    alerts = tracker.log_operation(op_type, desc, cost)
    click.echo(f"✅ Logged: {op_type} (${cost})")
    for alert in alerts:
        icon = "🔴" if alert.level == "critical" else "🟡"
        click.echo(f"{icon} {alert.message}")


@resources_cli.command(name="status")
def resources_status():
    """Show current resource status."""
    tracker = ResourceTracker()
    tracker.print_status()


@resources_cli.command(name="report")
def resources_report():
    """Generate resource usage report."""
    tracker = ResourceTracker()
    tracker.generate_report()


# Decision Audit Commands
@self_improvement_cli.group(name="decisions")
def decisions_cli():
    """Decision audit logging."""
    pass


@decisions_cli.command(name="log")
@click.argument("decision")
@click.argument("context", default="")
@click.argument("expected", default="success")
def decisions_log(decision: str, context: str, expected: str):
    """Log a decision."""
    logger = DecisionAuditLogger()
    decision_id = logger.log_decision(decision, context, expected)
    click.echo(f"Logged decision: {decision_id}")


@decisions_cli.command(name="outcome")
@click.argument("decision_id")
@click.argument("outcome")
@click.argument("correct", type=bool, default=True)
def decisions_outcome(decision_id: str, outcome: str, correct: bool):
    """Record outcome for a decision."""
    logger = DecisionAuditLogger()
    if logger.record_outcome(decision_id, outcome, correct):
        click.echo(f"✅ Recorded outcome for {decision_id}")
    else:
        click.echo(f"❌ Decision {decision_id} not found")


@decisions_cli.command(name="report")
def decisions_report():
    """Generate decision audit report."""
    logger = DecisionAuditLogger()
    logger.generate_report()


@decisions_cli.command(name="recent")
def decisions_recent():
    """Show recent decisions."""
    logger = DecisionAuditLogger()
    logger.print_recent()


@decisions_cli.command(name="get")
@click.argument("decision_id")
def decisions_get(decision_id: str):
    """Get a specific decision."""
    import json

    logger = DecisionAuditLogger()
    decision = logger.get_decision(decision_id)
    if decision:
        click.echo(json.dumps(decision, indent=2))
    else:
        click.echo(f"Decision {decision_id} not found")


def register_self_improvement_cli(main_group: click.Group) -> None:
    """Register self-improvement CLI with main CLI group."""
    main_group.add_command(self_improvement_cli)
