"""D22 operator contract over the owner-controlled Save Internet queue."""

from __future__ import annotations

import hashlib
import html as html_lib
import json
import re
from pathlib import Path
from typing import Literal
from urllib.parse import quote, urlsplit
from urllib.request import ProxyHandler, build_opener

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

from .save_internet_api import SERVICE
from .save_internet_core import ContentParser, classify_page


class D22Create(BaseModel):
    source_url: str = Field(min_length=12, max_length=2048)
    article_limit: int = Field(default=16000, ge=1, le=16000)
    depth: int = Field(default=2, ge=1, le=3)
    storage_limit_gib: float = Field(default=10, gt=0, le=4000)
    destination: Literal["archive", "research"] = "archive"
    pace: Literal["gentle", "slow", "manual"] = "gentle"
    include_images: bool = True
    respect_robots: bool = True
    pause_on_network: bool = True
    catalog_only: bool = True
    consent: bool


class D22BrowserCapture(BaseModel):
    final_url: str = Field(min_length=12, max_length=2048)
    title: str = Field(default="", max_length=500)
    html: str = Field(min_length=80, max_length=20 * 1024 * 1024)


PACE = {"gentle": (8, 20), "slow": (15, 35), "manual": (45, 90)}
BROWSER_STATUSES = ["browser_required", "browser_running", "browser_failed", "review_required"]


def _ensure_queue() -> bool:
    """Make the API self-healing if the in-process dispatcher disappeared."""
    dispatcher = getattr(SERVICE, "_dispatcher", None)
    if dispatcher is None or not dispatcher.is_alive():
        SERVICE.start()
        dispatcher = getattr(SERVICE, "_dispatcher", None)
    return bool(dispatcher and dispatcher.is_alive())


def _public(job: dict) -> dict:
    value = dict(job)
    value["d22"] = True
    value["d22_contract"] = value.get("d22_contract") or "D22_RECEIVER_V1"
    return value


def _browser_text(source: str) -> str:
    value = re.sub(r"(?is)<(script|style|noscript).*?>.*?</\1>", " ", source)
    value = re.sub(r"(?s)<[^>]+>", " ", value)
    return re.sub(r"\s+", " ", html_lib.unescape(value)).strip()


def _browser_review_required(title: str, source: str) -> bool:
    # Ignore hidden theme/plugin JavaScript strings such as captcha_placeholder.
    sample = f"{title} {_browser_text(source)[:200000]}".lower()
    return bool(re.search(r"captcha|verify you are human|cloudflare|sign in|log in|войти|капч", sample))


def _browser_access_gated(source: str) -> bool:
    """Detect an explicit publisher access gate without attempting to bypass it."""
    sample = source[:200000].lower()
    return bool(re.search(r"['\"]accesstype['\"]\s*:\s*['\"]gated|['\"]meterstate['\"]\s*:\s*['\"]gated", sample))


def register_d22_receiver_api(app: FastAPI) -> None:
    @app.get("/api/editor/v1/d22/health", tags=["d22"])
    async def d22_health() -> dict[str, object]:
        alive = _ensure_queue()
        return {
            "status": "ok" if alive else "degraded",
            "service": "d22-receiver",
            "queue": "save-internet-dispatcher",
            "dispatcher_alive": alive,
            "browser_fallback": "server2-loopback-bridge",
            "browser_statuses": BROWSER_STATUSES,
        }

    @app.get("/api/editor/v1/d22/jobs", tags=["d22"])
    async def list_d22_jobs(limit: int = 50) -> dict[str, list[dict]]:
        _ensure_queue()
        jobs = [item for item in SERVICE.list_jobs(limit=limit) if item.get("d22_contract") == "D22_RECEIVER_V1"]
        return {"items": [_public(item) for item in jobs]}

    @app.post("/api/editor/v1/d22/jobs", status_code=202, tags=["d22"])
    async def create_d22_job(payload: D22Create):
        if not payload.consent:
            raise HTTPException(status_code=400, detail="подтвердите разрешённый источник")
        if not _ensure_queue():
            raise HTTPException(status_code=503, detail="D22 очередь временно недоступна")
        min_delay, max_delay = PACE[payload.pace]
        source_host = (urlsplit(payload.source_url).hostname or "").lower().rstrip(".")
        if not source_host:
            raise HTTPException(status_code=400, detail="Не удалось определить домен источника")
        data = {
            "source_url": payload.source_url,
            "discovery_method": "section",
            "discovery_url": payload.source_url,
            "article_limit": payload.article_limit,
            "destination": payload.destination,
            "size_limit_bytes": int(payload.storage_limit_gib * 1024**3),
            "asset_max_bytes": 20 * 1024**2,
            "min_delay_seconds": min_delay,
            "max_delay_seconds": max_delay,
            "save_html": True,
            "save_images": False,
            "save_pdf": False,
            "respect_robots": payload.respect_robots,
            "rights_acknowledged": True,
            "d22_target_article_count": 16000,
            "d22_batch_size": 30,
            "d22_source_scope": source_host,
        }
        try:
            job = SERVICE.create_job(data)
            job = SERVICE._update(
                str(job["id"]),
                d22_contract="D22_RECEIVER_V1",
                d22_depth=payload.depth,
                d22_pace=payload.pace,
                d22_respect_robots=payload.respect_robots,
                d22_pause_on_network=payload.pause_on_network,
                d22_catalog_only=payload.catalog_only,
                d22_operator_source="services-d22-receiver.html",
                d22_target_article_count=16000,
                d22_batch_size=30,
                d22_source_scope=source_host,
            )
            SERVICE._wake.set()
            return {"job": _public(job)}
        except ValueError as exc:
            raise HTTPException(status_code=400, detail=str(exc)) from exc
        except Exception as exc:
            raise HTTPException(status_code=503, detail=f"D22 не смог поставить задание в очередь: {exc}") from exc

    @app.get("/api/editor/v1/d22/jobs/{job_id}", tags=["d22"])
    async def get_d22_job(job_id: str):
        _ensure_queue()
        try:
            job = SERVICE.get_job(job_id)
        except (KeyError, ValueError):
            raise HTTPException(status_code=404, detail="D22 job не найден") from None
        if job.get("d22_contract") != "D22_RECEIVER_V1":
            raise HTTPException(status_code=404, detail="D22 job не найден")
        return {"job": _public(job)}

    @app.post("/api/editor/v1/d22/jobs/{job_id}/browser-fallback/start", status_code=202, tags=["d22"])
    async def start_d22_browser_fallback(job_id: str):
        _ensure_queue()
        try:
            job = SERVICE.get_job(job_id)
        except (KeyError, ValueError):
            raise HTTPException(status_code=404, detail="D22 job не найден") from None
        if job.get("d22_contract") != "D22_RECEIVER_V1":
            raise HTTPException(status_code=404, detail="D22 job не найден")
        if job.get("status") not in {"browser_required", "browser_failed"}:
            raise HTTPException(status_code=409, detail="browser fallback доступен только для browser_required")
        target = str(job.get("current_url") or job.get("source_url") or "")
        bridge_url = f"http://127.0.0.1:8789/open?url={quote(target, safe='')}"
        try:
            with build_opener(ProxyHandler({})).open(bridge_url, timeout=45) as response:
                bridge = json.loads(response.read().decode("utf-8"))
        except Exception as exc:
            updated = SERVICE._update(job_id, status="browser_failed", status_reason=f"bridge недоступен: {exc}", message="browser bridge недоступен")
            return {"job": _public(updated), "bridge": {"status": "browser_failed"}}
        if bridge.get("status") != "browser_running":
            reason = str(bridge.get("error") or bridge.get("last_error") or "browser bridge не открыл страницу")
            updated = SERVICE._update(job_id, status="browser_failed", status_reason=reason, message="browser bridge не открыл страницу")
            return {"job": _public(updated), "bridge": bridge}
        updated = SERVICE._update(job_id, status="browser_running", browser_bridge_url=bridge_url, browser_started_at=SERVICE._read(job_id).get("updated_at"), message="страница открыта в разрешённом browser bridge")
        return {"job": _public(updated), "bridge": bridge}

    @app.post("/api/editor/v1/d22/jobs/{job_id}/browser-fallback/local-start", status_code=202, tags=["d22"])
    async def start_d22_local_browser_fallback(job_id: str):
        """Switch a D22 job to the browser service running on the operator PC."""
        _ensure_queue()
        try:
            job = SERVICE.get_job(job_id)
        except (KeyError, ValueError):
            raise HTTPException(status_code=404, detail="D22 job не найден") from None
        if job.get("d22_contract") != "D22_RECEIVER_V1":
            raise HTTPException(status_code=404, detail="D22 job не найден")
        if job.get("status") not in {"stopped_access", "browser_required", "browser_failed"}:
            raise HTTPException(status_code=409, detail="локальный браузер доступен после отказа HTTP или browser fallback")
        target = str(job.get("current_url") or job.get("source_url") or "")
        updated = SERVICE._update(
            job_id,
            status="browser_running",
            browser_bridge_url="local-browser-service:127.0.0.1:8765",
            browser_started_at=SERVICE._read(job_id).get("updated_at"),
            status_reason="",
            message="ожидается страница из браузера оператора",
        )
        SERVICE._event(job_id, "browser_required", "переключение на браузер оператора", url=target)
        return {"job": _public(updated), "target": target, "browser": "local"}

    @app.post("/api/editor/v1/d22/jobs/{job_id}/browser-fallback/capture", status_code=202, tags=["d22"])
    async def capture_d22_browser_fallback(job_id: str, payload: D22BrowserCapture):
        _ensure_queue()
        try:
            job = SERVICE.get_job(job_id)
        except (KeyError, ValueError):
            raise HTTPException(status_code=404, detail="D22 job не найден") from None
        if job.get("d22_contract") != "D22_RECEIVER_V1":
            raise HTTPException(status_code=404, detail="D22 job не найден")
        if job.get("status") != "browser_running":
            raise HTTPException(status_code=409, detail="browser capture требует browser_running")
        source_host = str(job.get("source_host") or "").lower().rstrip(".")
        final = urlsplit(payload.final_url)
        if final.scheme not in {"http", "https"} or (final.hostname or "").lower().rstrip(".") != source_host:
            updated = SERVICE._update(job_id, status="review_required", status_reason="browser final URL вышел за пределы исходного host", message="требуется ручная проверка адреса")
            return {"job": _public(updated)}
        if _browser_access_gated(payload.html):
            updated = SERVICE._update(job_id, status="review_required", status_reason="publisher access gate detected; no bypass", message="контент закрыт издателем; требуется ручная проверка доступа")
            return {"job": _public(updated)}
        if _browser_review_required(payload.title, payload.html):
            updated = SERVICE._update(job_id, status="review_required", status_reason="страница похожа на login/CAPTCHA/challenge", message="требуется ручная проверка страницы")
            return {"job": _public(updated)}
        parser = ContentParser(payload.final_url)
        parser.feed(payload.html)
        parser.finish()
        classification = classify_page(
            url=payload.final_url,
            parser=parser,
            status=200,
            content_type="text/html",
        )
        current = SERVICE._read(job_id)
        classifications = list(current.get("classification_results") or [])
        classifications.append({
            "ordinal": int(current.get("next_index") or 0) + 1,
            "url": payload.final_url,
            "final_url": payload.final_url,
            "visible_title": parser.title or payload.title,
            "published_at": parser.published_at,
            "canonical_candidates": list(parser.canonical_candidates),
            **classification,
        })
        SERVICE._update(job_id, classification_results=classifications)
        SERVICE._event(
            job_id,
            "classify_completed",
            "browser fallback страница классифицирована classifier v1",
            url=payload.final_url,
            ordinal=int(current.get("next_index") or 0) + 1,
            decision=classification["decision"],
            reason_code=classification["reason_code"],
            classifier_version=classification["version"],
        )
        # A source homepage is a discovery catalog, not an article. Keep its
        # links and let the normal crawler classify each linked page.
        if (
            classification["reason_code"] == "EXCLUDE_SERVICE"
            and payload.final_url.rstrip("/") == str(job.get("source_url") or "").rstrip("/")
            and parser.links
        ):
            candidates, evidence = SERVICE._filter_candidates_with_evidence(job, parser.links)
            candidates = candidates[: int(job.get("article_limit") or 16000)]
            updated = SERVICE._update(
                job_id,
                status="queued" if candidates else "failed",
                candidate_urls=candidates,
                candidate_evidence=evidence,
                current_url=None,
                browser_discovery=True,
                message=f"browser discovery: найдено ссылок: {len(candidates)}" if candidates else "browser discovery: ссылки не найдены",
                status_reason="" if candidates else "не найдено ссылок на источнике",
            )
            SERVICE._event(job_id, "discovery_completed", "browser discovery каталога завершён", source_url=payload.final_url, accepted=len(candidates), rejected=len(evidence) - len(candidates))
            SERVICE._wake.set()
            return {"job": _public(updated), "classification": classification, "discovered": len(candidates)}
        archive = SERVICE._archive_dir(job)
        raw_dir = archive / "raw-html"
        text_dir = archive / "text"
        manifest_dir = archive / "manifests"
        for folder in (raw_dir, text_dir, manifest_dir):
            folder.mkdir(parents=True, exist_ok=True)
        digest = hashlib.sha256(payload.html.encode("utf-8")).hexdigest()
        stem = f"browser-{digest[:16]}"
        raw_path = raw_dir / f"{stem}.html"
        text_path = text_dir / f"{stem}.txt"
        manifest_path = manifest_dir / f"{stem}.json"
        if classification["decision"] != "INCLUDE":
            next_index = int(current.get("next_index") or 0) + 1
            remaining = next_index < len(current.get("candidate_urls") or [])
            updated = SERVICE._update(
                job_id,
                status="queued" if remaining else "completed",
                next_index=next_index,
                skipped_pages=int(current.get("skipped_pages") or 0) + 1,
                current_url=None,
                browser_receipt=True,
                message=f"browser fallback: страница исключена classifier v1 ({classification['reason_code']})",
            )
            if remaining:
                SERVICE._wake.set()
            else:
                SERVICE._write_receipt(job_id)
            return {"job": _public(updated), "classification": classification, "receipt": str(archive / "receipt.json")}
        raw_path.write_text(payload.html, encoding="utf-8")
        text_path.write_text(_browser_text(payload.html), encoding="utf-8")
        manifest_path.write_text(json.dumps({"source_url": job.get("source_url"), "final_url": payload.final_url, "title": payload.title, "source_sha256": digest, "browser_fallback": True, "classification": classification}, ensure_ascii=False, indent=2), encoding="utf-8")
        SERVICE._add_bytes(job_id, raw_path.stat().st_size + text_path.stat().st_size + manifest_path.stat().st_size)
        next_index = int(current.get("next_index") or 0) + 1
        remaining = next_index < len(current.get("candidate_urls") or [])
        updated = SERVICE._update(job_id, status="queued" if remaining else "completed", saved_pages=int(job.get("saved_pages") or 0) + 1, next_index=next_index, current_url=None, browser_receipt=True, message="browser fallback сохранён")
        if remaining:
            SERVICE._wake.set()
        else:
            SERVICE._write_receipt(job_id)
        return {"job": _public(updated), "receipt": str(archive / "receipt.json"), "source_sha256": digest}

    @app.post("/api/editor/v1/d22/jobs/{job_id}/{action}", tags=["d22"])
    async def control_d22_job(job_id: str, action: Literal["pause", "resume", "stop"]):
        _ensure_queue()
        try:
            current = SERVICE.get_job(job_id)
            if current.get("d22_contract") != "D22_RECEIVER_V1":
                raise KeyError(job_id)
            return {"job": _public(SERVICE.action(job_id, action))}
        except KeyError:
            raise HTTPException(status_code=404, detail="D22 job не найден") from None
        except ValueError as exc:
            raise HTTPException(status_code=409, detail=str(exc)) from exc
