"""CLI entry point for priorart."""

from __future__ import annotations

from typing import Annotated

import typer

from priorart.formatters import format_json, format_markdown, format_table
from priorart.scanner import scan

app = typer.Typer(
    name="priorart",
    help="Scan GitHub and Hacker News for prior art on an idea.",
    add_completion=False,
)


@app.callback(invoke_without_command=True)
def main(ctx: typer.Context) -> None:
    """Prior art scanner — search GitHub and HN for existing solutions."""
    if ctx.invoked_subcommand is None:
        typer.echo(ctx.get_help())
        raise typer.Exit()


@app.command("scan")
def scan_cmd(
    idea: Annotated[str, typer.Argument(help="Idea description to scan")],
    format: Annotated[
        str,
        typer.Option(
            "--format",
            "-f",
            help="Output format: json, markdown, or table",
        ),
    ] = "table",
    sources: Annotated[
        str,
        typer.Option(
            "--sources",
            "-s",
            help="Comma-separated sources to query (github,hn)",
        ),
    ] = "github,hn",
    github_token: Annotated[
        str | None,
        typer.Option(
            "--github-token",
            envvar="GITHUB_TOKEN",
            help="GitHub personal access token (or set GITHUB_TOKEN env var)",
            show_default=False,
        ),
    ] = None,
) -> None:
    """Scan for prior art on an idea."""
    fmt = format.lower().strip()
    if fmt not in ("json", "markdown", "table"):
        typer.echo(
            f"Error: invalid format '{fmt}'. Choose from: json, markdown, table",
            err=True,
        )
        raise typer.Exit(code=1)

    source_list = [s.strip().lower() for s in sources.split(",") if s.strip()]
    for s in source_list:
        if s not in ("github", "hn"):
            typer.echo(
                f"Error: unknown source '{s}'. Choose from: github, hn",
                err=True,
            )
            raise typer.Exit(code=1)

    if "github" in source_list and not github_token:
        typer.echo(
            "Note: No GITHUB_TOKEN set. GitHub search will work but is "
            "rate-limited (10 req/min). Set GITHUB_TOKEN for higher limits.",
            err=True,
        )

    result = scan(idea, github_token=github_token, sources=source_list)

    if fmt == "json":
        typer.echo(format_json(result))
    elif fmt == "markdown":
        typer.echo(format_markdown(result))
    else:
        typer.echo(format_table(result))


if __name__ == "__main__":
    app()
