"""
SAM3 license acceptance gate.

Meta's SAM3 model weights are distributed under the SAM License. This module
ensures users accept the license before downloading or using the weights, and
writes a copy of the license alongside downloaded weights as required by the
license terms.

Acceptance is persisted in the SDK config file (~/.highlighter/config) under
[licenses] sam3_accepted = true.
"""

import logging
import shutil
import sys
from pathlib import Path

import click

logger = logging.getLogger(__name__)

# Known SAM3 system artefact UUID (must match MachineAgent.std_sam3_artefact_id)
SAM3_ARTEFACT_UUID = "be3fd409-73a2-48b1-81e0-3a2e492f246c"

SAM3_LICENSE_URL = "https://github.com/facebookresearch/sam3/blob/main/LICENSE"

_BUNDLED_LICENSE_PATH = Path(__file__).parent / "SAM_LICENSE"


def is_sam3_artefact(artefact_uuid: str) -> bool:
    """Check whether an artefact UUID is the known SAM3 system artefact."""
    return str(artefact_uuid).strip().lower() == SAM3_ARTEFACT_UUID.lower()


def write_license_file(weights_path: Path) -> Path:
    """Copy the SAM License file next to the downloaded weights.

    Returns the path to the written license file.
    """
    dest = weights_path.parent / "SAM_LICENSE"
    shutil.copy2(_BUNDLED_LICENSE_PATH, dest)
    return dest


def _is_accepted_in_config() -> bool:
    from highlighter.core.config import HighlighterRuntimeConfig

    try:
        cfg = HighlighterRuntimeConfig.load()
        return cfg.licenses.sam3_accepted
    except Exception:
        return False


def _save_acceptance_to_config() -> None:
    from highlighter.core.config import HighlighterRuntimeConfig

    try:
        cfg = HighlighterRuntimeConfig.load()
        cfg.licenses.sam3_accepted = True
        cfg.save()
    except Exception as exc:
        logger.warning("Could not save SAM3 license acceptance to config: %s", exc)


def require_acceptance() -> None:
    """Ensure the user has accepted the SAM3 license before proceeding.

    Checks the SDK config file for prior acceptance. If not found, shows a
    link to the license and prompts interactively. On acceptance, persists
    the choice to the config file.

    Raises click.ClickException in non-interactive contexts, click.Abort on
    decline.
    """
    if _is_accepted_in_config():
        return

    click.echo()
    click.echo(
        "The SAM3 model weights are distributed under Meta's SAM License.\n"
        f"Read the full license at: {SAM3_LICENSE_URL}\n"
    )
    click.echo("You must accept these terms to download and use the weights.\n")

    if not sys.stdin.isatty():
        raise click.ClickException(
            "SAM3 license must be accepted before downloading weights. "
            "Set [licenses] sam3_accepted = true in your Highlighter "
            "config file (~/.highlighter/config)."
        )

    if not click.confirm("Do you accept the SAM3 license terms?"):
        raise click.Abort()

    _save_acceptance_to_config()
    click.echo("License accepted. Saved to config.\n")
