import typer
import json
from typing import Annotated
from nixprstatus.pr import pr_merge_status
from nixprstatus.pr import commits_since
from nixprstatus.watchlist import Watchlist
from nixprstatus.output import OutputFormat

app = typer.Typer(rich_markup_mode=None)
watchlist_app = typer.Typer()
app.add_typer(watchlist_app, name="watchlist", help="Manage watchlist.")

DEFAULT_HEADERS = {
    "Accept": "application/vnd.github.text+json",
}

BRANCHES = ["nixos-unstable-small", "nixos-unstable", "nixos-24.05"]


@app.command()
def pr(
    pr: list[int],
    branches: Annotated[
        list[str] | None, typer.Option(help="Check specific branch")
    ] = None,
    format: Annotated[
        OutputFormat, typer.Option(help="Output format")
    ] = OutputFormat.CONSOLE,
) -> None:
    """Get merge status of pull request(s)."""
    for pr_ in pr:
        status = pr_merge_status(pr_, branches)
        status.print(format=format)
        if format != OutputFormat.JSON:
            print()


@app.command()
def since(
    commit_sha: str,
    target: str = "nixos-unstable",
    waybar_format: Annotated[
        bool, typer.Option(help="Output in format expected by waybar")
    ] = False,
) -> None:
    """
    Return the count of commits that has happened between the two refs.
    """
    count = commits_since(target, commit_sha)

    if waybar_format:
        output = {"text": str(count), "tooltip": f"{target}: {count}"}
        typer.echo(json.dumps(output))
        return
    typer.echo(count)


@watchlist_app.command(name="list")
def command_list(
    watchlist: str | None = None, format: OutputFormat = OutputFormat.CONSOLE
) -> None:
    """List PRs in watchlist."""
    wl = Watchlist.from_file(path=watchlist)
    wl.print(format=format)


@watchlist_app.command()
def add(pr: int, watchlist: str | None = None) -> None:
    """Add PR to watchlist."""
    wl = Watchlist.from_file(path=watchlist)
    info = wl.add_pr(pr)
    wl.to_file(path=watchlist)
    print(f"Added #{info.pr}: {info.title} to watchlist.")


@watchlist_app.command()
def remove(pr: int) -> None:
    """Remove PR from watchlist."""
    wl = Watchlist.from_file()
    if pr not in wl:
        print(f"#{pr} not in watchlist.")
        return
    wl.remove(pr)
    wl.to_file()
    print(f"Removed #{pr} from watchlist.")
