"""Command-line interface for Neuralk SDK."""

import os

import click

from neuralk.neuralk import get_access_token


@click.group()
def main():
    """Neuralk SDK command-line interface."""
    pass


@main.command()
def login():
    """Display instructions to create an account and get an API key."""
    get_access_token()


@main.group()
def terms():
    """View and accept the Neuralk Terms of Service."""
    pass


@terms.command("show")
def terms_show():
    """Display the current Terms of Service version and URL."""
    from neuralk._api import NeuralkAPI

    client = NeuralkAPI()
    try:
        info = client.get_terms()
    except Exception as exc:
        raise click.ClickException(str(exc)) from exc

    click.echo(f"Terms version : {info.get('current_version', 'unknown')}")
    click.echo(f"Full text     : {info.get('url', 'N/A')}")


@terms.command("accept")
@click.option(
    "--api-key",
    envvar="NEURALK_API_KEY",
    default=None,
    help="API key (or set NEURALK_API_KEY).",
)
@click.option(
    "--yes", "-y",
    is_flag=True,
    default=False,
    help="Skip confirmation prompt.",
)
def terms_accept(api_key: str | None, yes: bool):
    """Accept the current Terms of Service."""
    from neuralk._api import NeuralkAPI

    if not api_key:
        api_key = os.environ.get("NEURALK_API_KEY")
    if not api_key:
        raise click.ClickException(
            "An API key is required. Pass --api-key or set NEURALK_API_KEY."
        )

    client = NeuralkAPI(api_key=api_key)

    try:
        info = client.get_terms()
    except Exception as exc:
        raise click.ClickException(str(exc)) from exc

    version = info.get("current_version", "unknown")
    url = info.get("url", "N/A")

    click.echo(f"Terms version : {version}")
    click.echo(f"Full text     : {url}")

    if not yes:
        click.confirm(
            f"Do you accept the Terms of Service ({version})?",
            abort=True,
        )

    try:
        client.accept_terms(version)
    except Exception as exc:
        raise click.ClickException(str(exc)) from exc

    click.echo(f"Terms of Service {version} accepted.")
