"""ievo learn — self-evolution commands."""

from __future__ import annotations

import typer
from rich.markdown import Markdown

from ievo.core.config import AGENTS_DIR, require_project
from ievo.core.project import ProjectManifest
from ievo.utils.console import console, info, success

app = typer.Typer(no_args_is_help=True)


@app.command(name="log")
def log(
    agent: str = typer.Argument(help="Agent name."),
    last: int = typer.Option(0, "--last", "-n", help="Show last N entries (0 = all)."),
) -> None:
    """[DEPRECATED] Show evolution history for an agent."""
    from ievo.utils.deprecation import deprecated_command

    deprecated_command("ievo learn log")
    root = require_project()
    evo_log = root / AGENTS_DIR / agent / "EVOLUTION_LOG.md"

    if not evo_log.exists():
        info(f"No evolution log for [bold]{agent}[/bold] yet.")
        return

    content = evo_log.read_text().strip()
    if not content or content == "# Evolution Log":
        info(f"[bold]{agent}[/bold] hasn't evolved yet. Make some mistakes first!")
        return

    if last > 0:
        # Split by ## headers and take last N
        sections = content.split("\n## ")
        header = sections[0]
        entries = sections[1:] if len(sections) > 1 else []
        entries = entries[-last:]
        content = header + "\n\n## " + "\n\n## ".join(entries) if entries else content

    console.print(Markdown(content))


@app.command(name="push")
def push(
    agent: str | None = typer.Argument(default=None, help="Agent name (all if omitted)."),
) -> None:
    """[DEPRECATED] Send anonymized evolution logs to marketplace (opt-in)."""
    from ievo.utils.deprecation import deprecated_command

    deprecated_command("ievo learn push")
    root = require_project()
    manifest = ProjectManifest.load(root)

    agents_to_push = [agent] if agent else list(manifest.agents.keys())

    for a in agents_to_push:
        evo_log = root / AGENTS_DIR / a / "EVOLUTION_LOG.md"
        if evo_log.exists() and evo_log.read_text().strip() != "# Evolution Log":
            info(f"Pushing evolution log for [bold]{a}[/bold]...")
            # TODO: implement actual REST API call
            success(f"{a} — log pushed (anonymized)")
        else:
            info(f"{a} — no evolution data to push")

    info("[dim]Logs are anonymized. No project data or code is shared.[/dim]")


@app.command(name="status")
def status(
    agent: str | None = typer.Argument(default=None, help="Agent name (all if omitted)."),
) -> None:
    """[DEPRECATED] Show evolution statistics for agent(s)."""
    from ievo.utils.deprecation import deprecated_command

    deprecated_command("ievo learn status")
    root = require_project()
    manifest = ProjectManifest.load(root)

    agents_to_check = [agent] if agent else list(manifest.agents.keys())

    for a in agents_to_check:
        evo_log = root / AGENTS_DIR / a / "EVOLUTION_LOG.md"
        role_md = root / AGENTS_DIR / a / "ROLE.md"

        evo_count = 0
        if evo_log.exists():
            content = evo_log.read_text()
            evo_count = content.count("\n## ")

        role_lines = 0
        if role_md.exists():
            role_lines = len(role_md.read_text().splitlines())

        console.print(
            f"  [bold]{a}[/bold]  "
            f"[dim]evolutions:[/dim] {evo_count}  "
            f"[dim]ROLE.md:[/dim] {role_lines} lines"
        )
