"""High-level image verification against the Tectra provenance network."""

from __future__ import annotations

import logging
from pathlib import Path
from typing import Union

import httpx

from tectra_verify.hashing import compute_hashes, compute_sha256
from tectra_verify.watermark import extract_watermark

logger = logging.getLogger(__name__)

DEFAULT_API_URL = "https://tectra.vision"


def verify_image(
    image_path_or_bytes: Union[str, Path, bytes],
    *,
    api_url: str = DEFAULT_API_URL,
    timeout: float = 30.0,
) -> dict:
    """Verify an image's provenance via the Tectra network.

    This is the main entry point for verification. It:

    1. Computes SHA-256 and perceptual hashes locally.
    2. Attempts to extract an embedded watermark.
    3. Sends the local evidence to the Tectra verification API.
    4. Returns the combined result.

    Parameters
    ----------
    image_path_or_bytes:
        A file path (``str`` or ``Path``) or raw image bytes.
    api_url:
        Base URL of the Tectra verification API.
    timeout:
        HTTP request timeout in seconds.

    Returns
    -------
    dict
        Verification result containing at minimum:

        - ``verified`` (bool): overall pass/fail
        - ``sha256`` (str): image digest
        - ``phash`` (str): perceptual hash
        - ``watermark_found`` (bool): whether a watermark was extracted
        - ``api_response`` (dict | None): raw API response, or ``None``
          if the API was unreachable
    """
    if isinstance(image_path_or_bytes, (str, Path)):
        image_bytes = Path(image_path_or_bytes).read_bytes()
    else:
        image_bytes = image_path_or_bytes

    hashes = compute_hashes(image_bytes)
    watermark = extract_watermark(image_bytes)

    result: dict = {
        "verified": False,
        "sha256": hashes["sha256"],
        "phash": hashes["phash"],
        "watermark_found": len(watermark) > 0 and watermark != b"\x00" * len(watermark),
        "watermark_hex": watermark.hex() if watermark else None,
        "api_response": None,
    }

    payload = {
        "sha256": hashes["sha256"],
        "phash": hashes["phash"],
        "watermark_hex": result["watermark_hex"],
    }

    try:
        with httpx.Client(timeout=timeout) as client:
            resp = client.post(
                f"{api_url.rstrip('/')}/api/v1/verify",
                json=payload,
            )
            resp.raise_for_status()
            api_data = resp.json()
            result["api_response"] = api_data
            result["verified"] = api_data.get("verified", False)
    except httpx.HTTPError as exc:
        logger.warning("Verification API request failed: %s", exc)
    except Exception:
        logger.warning("Unexpected error contacting verification API", exc_info=True)

    return result
