"""CLI entry point for lens."""

import click
from rich.console import Console

from prlens.config import load_config
from prlens.gh.pull_request import get_repo, get_pull_requests
from prlens.reviewer import run_review

console = Console()


@click.command()
@click.option("--repo", required=True, help="GitHub repository in owner/name format.")
@click.option(
    "--pr",
    "pr_number",
    type=int,
    default=None,
    help="Pull request number. Omit to list open PRs interactively.",
)
@click.option(
    "--model",
    type=click.Choice(["anthropic", "openai"]),
    default=None,
    help="AI model provider. Overrides config file.",
)
@click.option(
    "--guidelines",
    "guidelines_path",
    default=None,
    help="Path to a Markdown guidelines file. Overrides config file.",
)
@click.option(
    "--config",
    "config_path",
    default=".prlens.yml",
    show_default=True,
    help="Path to the configuration file.",
)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Skip confirmation prompts and post comments automatically.",
)
@click.option(
    "--shadow",
    "-s",
    is_flag=True,
    help="Dry-run mode: print review comments to the terminal without posting to GitHub.",
)
def main(repo: str, pr_number: int | None, model: str | None, guidelines_path: str | None, config_path: str, yes: bool, shadow: bool):
    """AI-powered GitHub PR code reviewer.

    Fetches a pull request, reviews each changed file against your coding
    guidelines using Claude or GPT-4o, and posts inline comments on GitHub.

    \b
    Required environment variables:
      GITHUB_TOKEN         GitHub personal access token
      ANTHROPIC_API_KEY    Required when using --model anthropic
      OPENAI_API_KEY       Required when using --model openai
    """
    config = load_config(config_path, cli_overrides={"model": model, "guidelines": guidelines_path})

    if not config.get("github_token"):
        raise click.UsageError(
            "GITHUB_TOKEN environment variable is not set. "
            "Create a token at https://github.com/settings/tokens"
        )
    if config["model"] == "anthropic" and not config.get("anthropic_api_key"):
        raise click.UsageError("ANTHROPIC_API_KEY environment variable is not set.")
    if config["model"] == "openai" and not config.get("openai_api_key"):
        raise click.UsageError("OPENAI_API_KEY environment variable is not set.")

    if pr_number is None:
        this_repo = get_repo(repo, token=config["github_token"])
        prs = list(get_pull_requests(this_repo))
        if not prs:
            console.print("[yellow]No open pull requests found.[/yellow]")
            return
        console.print("\nOpen pull requests:")
        for pr in prs:
            console.print(f"  [bold]#{pr.number}[/bold]  {pr.title}")
        pr_number = click.prompt("\nEnter the pull request number", type=int)

    run_review(repo=repo, pr_number=pr_number, config=config, auto_confirm=yes, shadow=shadow)
