"""Draft generation and proposal intake commands."""

from __future__ import annotations

from pathlib import Path

import click

from .common import console, _get_config
from ..config import Config
from ..db import Database


def register(main):
    """Register all proposal commands with the main CLI group."""
    main.add_command(draft_gen)
    main.add_command(intake)


# ── draft-gen ───────────────────────────────────────────────────────────


@click.command("draft-gen")
@click.argument("gap_topic")
@click.option("--output", "-o", help="Output file path")
def draft_gen(gap_topic: str, output: str | None):
    """Generate an Internet-Draft addressing a landscape gap."""
    from ..draftgen import DraftGenerator
    from ..analyzer import Analyzer

    cfg = _get_config()
    db = Database(cfg)
    analyzer = Analyzer(cfg, db)
    generator = DraftGenerator(cfg, db, analyzer)

    try:
        out_path = output or str(Path(cfg.data_dir) / "reports" / "generated-draft.txt")
        console.print(f"Generating Internet-Draft on: [bold]{gap_topic}[/]")
        path = generator.generate(gap_topic, output_path=out_path)
        console.print(f"\nDraft saved: [bold green]{path}[/]")
    finally:
        db.close()


# ── proposal intake ──────────────────────────────────────────────────────────


@click.command("intake")
@click.argument("input_text", required=False)
@click.option("--file", "-f", type=click.Path(exists=True), help="Read input from a file")
@click.option("--dry-run", is_flag=True, help="Parse and show proposals without storing")
def intake(input_text: str | None, file: str | None, dry_run: bool):
    """Generate draft proposals from text/URLs.

    Paste article text, URLs, or notes. Claude analyzes against all gaps
    and generates structured IETF draft proposals automatically.

    Examples:

        ietf intake "https://arxiv.org/abs/2503.18813"

        ietf intake -f notes.txt

        echo "interesting paper about agent security" | ietf intake -
    """
    from ..proposal_intake import ProposalIntake

    if input_text == "-":
        import sys
        input_text = sys.stdin.read()
    elif file:
        input_text = Path(file).read_text()
    elif not input_text:
        # Interactive: read from stdin until EOF
        console.print("[dim]Paste text/URLs, then Ctrl+D to submit:[/]")
        import sys
        input_text = sys.stdin.read()

    if not input_text or not input_text.strip():
        console.print("[red]No input provided.[/]")
        raise SystemExit(1)

    cfg = _get_config()
    db = Database(cfg)
    try:
        pipeline = ProposalIntake(cfg, db)
        proposals, usage = pipeline.process(input_text, dry_run=dry_run)

        if proposals:
            console.print(f"\n[bold green]{len(proposals)} proposal(s) generated[/]")
            for p in proposals:
                pid = p.get("id", "---")
                gaps = ", ".join(f"#{g}" for g in p.get("gap_ids", []))
                console.print(f"  [blue]#{pid}[/] {p['title']}  [dim]gaps: {gaps}[/]")
            if not dry_run:
                console.print(f"\nView in web UI: [bold]http://localhost:5000/proposals[/]")
        else:
            console.print("[yellow]No proposals generated from this input.[/]")
    finally:
        db.close()
