"""Command-line interface for tectra-verify."""

from __future__ import annotations

import json
import sys
from pathlib import Path

import click

from tectra_verify.verify import DEFAULT_API_URL, verify_image


@click.group()
@click.version_option(package_name="tectra-verify")
def main() -> None:
    """Tectra image provenance verification."""


@main.command()
@click.argument("file", type=click.Path(exists=True, dir_okay=False, path_type=Path))
@click.option(
    "--api-url",
    default=DEFAULT_API_URL,
    show_default=True,
    help="Tectra verification API base URL.",
)
@click.option("--json-output", is_flag=True, help="Output raw JSON instead of formatted text.")
def check(file: Path, api_url: str, json_output: bool) -> None:
    """Verify the provenance of an image FILE."""
    result = verify_image(file, api_url=api_url)

    if json_output:
        click.echo(json.dumps(result, indent=2))
        return

    _print_result(result)

    if not result["verified"]:
        sys.exit(1)


def _print_result(result: dict) -> None:
    """Pretty-print a verification result to stdout."""
    verified = result["verified"]
    status = click.style("VERIFIED", fg="green", bold=True) if verified else click.style(
        "NOT VERIFIED", fg="red", bold=True
    )

    click.echo(f"\n  Status:     {status}")
    click.echo(f"  SHA-256:    {result['sha256']}")
    click.echo(f"  pHash:      {result['phash']}")
    click.echo(f"  Watermark:  {'found' if result['watermark_found'] else 'none'}")

    api = result.get("api_response")
    if api is None:
        click.echo(click.style("  API:        unreachable", fg="yellow"))
    else:
        click.echo(f"  API:        responded")

    click.echo()
