#!/usr/bin/env python3
"""Extract pricing with evidence. Run with Python 3.10+ and DATASEA_API_KEY."""

import json
import os
import re
import sys
import time
from email.utils import parsedate_to_datetime
from http.client import HTTPException
from pathlib import Path
from queue import Empty, Queue
from threading import Thread
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
from uuid import uuid4

API_URL = "https://api.datasea.io"
FIXTURE_URL = "https://developers.datasea.io/examples/benchmark/fixtures/pricing-v1.html"
INSTRUCTION = (
    "Extract one row for each subscription plan explicitly listed on the page, including quote-only plans. "
    "Exclude add-ons. Copy the plan name, price including its currency as written, and the billing interval "
    "as exact text from the page. Set price or billingInterval to null when it is not stated. "
    "For every non-null field, cite the full sentence from the page that supports it."
)
FIELDS = ("plan", "price", "billingInterval")


def object_schema(properties):
    return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False}


SCHEMA = object_schema({
    "rows": {"type": "array", "items": object_schema({
        "plan": {"type": "string"},
        "price": {"type": ["string", "null"]},
        "billingInterval": {"type": ["string", "null"]},
    })},
})
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
UNAVAILABLE_CODES = {"operation_disabled", "format_disabled", "structured_extraction_unavailable"}
TERMINAL_FAILURES = {"completed_with_errors", "failed", "cancelled", "expired"}
MAX_RESPONSE_BYTES = 2 * 1024 * 1024
KEY_PATTERN = r"[A-Za-z0-9_.:-]{1,128}"


class APIError(Exception):
    def __init__(self, code, *, status=None, request_id=None, retry_after=None, retryable=False):
        super().__init__(code)
        self.code = code
        self.status = status
        self.request_id = request_id
        self.retry_after = retry_after
        self.retryable = retryable
        self.job = None


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        # Do not forward credentials to a URL returned by the server.
        return None


def web_url(url, *, api=False):
    parts = urlsplit(url)
    if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username is not None:
        raise ValueError("Expected an HTTP(S) URL without credentials")
    if api and (
        parts.path not in {"", "/"} or parts.query or parts.fragment
        or (parts.scheme != "https" and parts.hostname not in {"localhost", "127.0.0.1", "::1"})
    ):
        raise ValueError("DATASEA_API_URL must be an HTTPS origin or an HTTP loopback origin")
    return url.rstrip("/") if api else url


def request(url, headers, deadline, *, body=None, timeout=15):
    """Make one HTTP request. The caller's deadline also covers reading the response."""
    remaining = min(timeout, deadline - time.monotonic())
    if remaining <= 0:
        raise APIError("deadline_exceeded")

    result = Queue(maxsize=1)

    def perform():
        try:
            opener = build_opener(NoRedirect())
            call = Request(url, data=body, headers=headers, method="POST" if body is not None else "GET")
            try:
                response = opener.open(call, timeout=remaining)
            except HTTPError as error:
                response = error
            with response:
                raw = response.read(MAX_RESPONSE_BYTES + 1)
                if len(raw) > MAX_RESPONSE_BYTES:
                    raise APIError("response_too_large", status=response.code)
                result.put((response.code, response.headers, raw))
        except Exception as error:
            result.put(error)

    # Socket timeouts alone do not bound a slowly streamed response.
    Thread(target=perform, daemon=True).start()
    try:
        response = result.get(timeout=remaining)
    except Empty:
        raise APIError("request_timeout", retryable=True) from None
    if isinstance(response, (URLError, OSError, HTTPException)):
        raise APIError("transport_error", retryable=True) from None
    if isinstance(response, Exception):
        raise response
    return response


def require_success(status, headers, payload):
    if 200 <= status < 300:
        return
    detail = payload.get("error") if isinstance(payload, dict) else None
    code = detail.get("code") if isinstance(detail, dict) else detail
    if not isinstance(code, str) or not re.fullmatch(r"[a-zA-Z0-9_.-]{1,100}", code):
        code = f"http_{status}"
    retryable = (
        status in RETRYABLE_STATUS and code not in UNAVAILABLE_CODES
        and (not isinstance(detail, dict) or detail.get("retryable") is not False)
    )
    raise APIError(code, status=status, request_id=headers.get("X-Request-ID"),
                   retry_after=headers.get("Retry-After"), retryable=retryable)


def parse_json(raw):
    try:
        return json.loads(raw)
    except (ValueError, UnicodeError):
        raise APIError("invalid_json_response") from None


def pause(seconds, deadline):
    if time.monotonic() + seconds >= deadline:
        raise APIError("deadline_exceeded")
    time.sleep(seconds)


def retry_delay(header, attempt):
    if header:
        if re.fullmatch(r"[0-9]+", header):
            return int(header) if len(header) < 10 else float("inf")
        try:
            date = parsedate_to_datetime(header)
            if date.tzinfo is not None:
                return max(0, date.timestamp() - time.time())
        except (TypeError, ValueError, OverflowError):
            pass
    return 0.5 * 2**attempt


def fetch_job(url, headers, deadline, *, body=None):
    # POST callers supply the same Idempotency-Key and serialized body on every attempt.
    for attempt in range(3):
        try:
            status, response_headers, raw = request(url, headers, deadline, body=body)
            try:
                payload = parse_json(raw)
            except APIError:
                require_success(status, response_headers, None)
                raise
            job = payload.get("data") if isinstance(payload, dict) else None
            try:
                require_success(status, response_headers, payload)
            except APIError as error:
                if isinstance(job, dict) and job.get("id"):
                    error.job = job
                    error.retryable = False
                raise
            if (
                not isinstance(job, dict) or payload.get("success") is not True
                or not isinstance(job.get("id"), str)
                or not re.fullmatch(r"[\da-fA-F]{8}(?:-[\da-fA-F]{4}){3}-[\da-fA-F]{12}", job["id"], re.ASCII)
            ):
                raise APIError("invalid_job_response")
            return job
        except APIError as error:
            if not error.retryable or attempt == 2:
                raise
            pause(retry_delay(error.retry_after, attempt), deadline)


def extract(url, key, *, api_url=API_URL, idempotency_key=None, timeout=180, poll_interval=2, schema=None):
    deadline = time.monotonic() + timeout
    base = web_url(api_url, api=True)
    body = json.dumps({
        "url": web_url(url),
        "mode": "async",
        "options": {
            "formats": ["json"],
            "render": "never",
            "cache": {"mode": "bypass"},
            "timeoutMs": 30000,
            "mainContentOnly": False,
            "json": {"schema": SCHEMA, "instruction": INSTRUCTION} if schema is None else {"schema": schema},
        },
    }).encode("utf-8")
    stable_key = idempotency_key or str(uuid4())
    if not re.fullmatch(KEY_PATTERN, stable_key):
        raise ValueError("Use 1–128 letters, digits or ._:- in DATASEA_IDEMPOTENCY_KEY")
    headers = {"X-API-Key": key, "Accept": "application/json"}
    job = fetch_job(f"{base}/v1/scrape", {
        **headers, "Content-Type": "application/json", "Idempotency-Key": stable_key,
    }, deadline, body=body)

    job_id = job["id"]
    try:
        for poll in range(91):
            state = job.get("state")
            if state == "completed":
                result = job.get("result")
                outputs = result.get("outputs") if isinstance(result, dict) else None
                extracted = outputs.get("json") if isinstance(outputs, dict) else None
                if not isinstance(extracted, dict) or "data" not in extracted:
                    raise APIError("missing_json_output")
                return {
                    "jobId": job_id,
                    "requestId": job.get("requestId"),
                    "sourceUrl": result.get("finalUrl") or result.get("url"),
                    "capturedAt": result.get("capturedAt"),
                    "usage": job.get("usage"),
                    "warnings": job.get("warnings", []),
                    **{name: extracted.get(name) for name in ("data", "evidence", "missingFields", "generated", "model", "engine")},
                }
            if state in TERMINAL_FAILURES:
                detail = job.get("error")
                code = detail.get("code") if isinstance(detail, dict) else None
                raise APIError(code or state)
            if state not in {"queued", "running", "cancel_requested"}:
                raise APIError("unknown_job_state")
            if poll == 90:
                raise APIError("poll_limit_exceeded")
            pause(poll_interval, deadline)
            # Construct the documented status path on the same origin.
            polled = fetch_job(f"{base}/v1/jobs/{job_id}", headers, deadline)
            if polled["id"] != job_id:
                raise APIError("unexpected_job_id")
            job = polled
    except APIError as error:
        error.job = job
        raise


def main():
    if sys.argv[1:] in (["--help"], ["-h"]):
        print("Usage: DATASEA_API_KEY=... python3 extract.py [public-url [schema.json]]")
        return 0
    if len(sys.argv) > 3 or not (key := os.environ.get("DATASEA_API_KEY", "").strip()):
        print("Set DATASEA_API_KEY (scopes web:scrape and web:jobs:read) and pass an optional URL and schema file.", file=sys.stderr)
        return 2
    stable_key = os.environ.get("DATASEA_IDEMPOTENCY_KEY") or str(uuid4())
    if not re.fullmatch(KEY_PATTERN, stable_key):
        print("Use 1–128 letters, digits or ._:- in DATASEA_IDEMPOTENCY_KEY", file=sys.stderr)
        return 2
    print(f"Idempotency-Key: {stable_key}", file=sys.stderr)
    try:
        schema = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8")) if len(sys.argv) == 3 else None
        if len(sys.argv) == 3 and not isinstance(schema, dict):
            raise ValueError("The schema file must contain a JSON Schema object")
        result = extract(sys.argv[1] if len(sys.argv) >= 2 else FIXTURE_URL, key, schema=schema,
                         api_url=os.environ.get("DATASEA_API_URL") or API_URL, idempotency_key=stable_key)
    except (APIError, ValueError, OSError) as error:
        detail = {"error": str(error)}
        if isinstance(error, APIError):
            detail.update(status=error.status, requestId=error.request_id or (error.job or {}).get("requestId"), jobId=(error.job or {}).get("id"))
        print(json.dumps(detail), file=sys.stderr)
        return 1
    print(json.dumps(result, indent=2, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    sys.exit(main())
