"""Internet Archive fetcher (incl. Prelinger).

Metadata API: https://archive.org/metadata/<id> (keyless); search via
advancedsearch.php. License is read from `licenseurl`/`rights`/`license` and
normalized through tools.licensing. When no explicit license is present the
item is assumed public_domain and flagged in notes for review (§6.4); an
explicitly non-free license (e.g. All Rights Reserved) raises and is not
ingested.
"""

from __future__ import annotations

from tools.ingest.base import Candidate
from tools.licensing import normalize_license

META = "https://archive.org/metadata/"
SEARCH = "https://archive.org/advancedsearch.php"
_NO_LICENSE_CAVEAT = "[IA: no explicit license — assumed public_domain, verify before use]"
_MEDIA_EXTS = (
    ".mp4", ".mov", ".m4v", ".ogv", ".webm",
    ".mp3", ".m4a", ".wav", ".flac", ".ogg",
)


def _ext_from_name(name: str) -> str:
    return name.rsplit(".", 1)[-1].lower() if "." in name else ""


def _pick_file(files):
    originals = [f for f in files if f.get("source") == "original"]
    for pool in (originals, files):
        for f in pool:
            if str(f.get("name", "")).lower().endswith(_MEDIA_EXTS):
                return f
    return None


class InternetArchiveFetcher:
    archive = "internet_archive"

    def __init__(self, client):
        self.client = client

    def resolve(self, identifier: str) -> Candidate:
        data = self.client.get_json(f"{META}{identifier}")
        meta = data.get("metadata", {})
        files = data.get("files", []) or []
        server = data.get("server", "")
        directory = data.get("dir", "")

        chosen = _pick_file(files)
        media_url = ""
        media_ext = ""
        if chosen and server:
            name = chosen["name"]
            media_url = f"https://{server}{directory}/{name}"
            media_ext = _ext_from_name(name)

        raw_license = (
            meta.get("licenseurl") or meta.get("rights") or meta.get("license") or ""
        )
        creator = meta.get("creator", "") or ""
        if isinstance(creator, list):
            creator = ", ".join(str(c) for c in creator)
        description = (meta.get("description", "") or "").strip()

        ambiguous = (not raw_license) or ("no known copyright" in raw_license.lower())
        if raw_license:
            lic, attr = normalize_license(raw_license, creator=creator)
        else:
            lic, attr = "public_domain", ""
        if ambiguous:
            description = f"{description} {_NO_LICENSE_CAVEAT}".strip()

        return Candidate(
            source_archive=self.archive,
            source_url=f"https://archive.org/details/{identifier}",
            media_url=media_url,
            title=meta.get("title", identifier),
            license=lic,
            attribution=attr,
            suggested_id=f"ia-{identifier}",
            media_ext=media_ext,
            description=description,
        )

    def search(self, query: str, *, limit: int) -> list[Candidate]:
        url = f"{SEARCH}?q={query}&fl[]=identifier&rows={limit}&output=json"
        data = self.client.get_json(url)
        docs = (data.get("response", {}).get("docs") or [])[:limit]
        return [self.resolve(doc["identifier"]) for doc in docs]
