#!/usr/bin/env python3
"""Submit a URL list, wait for the service-selected content package, and save it."""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path


def request(url, method="GET", body=None, token=None):
    payload = None if body is None else json.dumps(body).encode()
    headers = {"User-Agent": "Relaxzine-ContentPackage/1.0"}
    if payload is not None:
        headers["Content-Type"] = "application/json"
    if token:
        headers["Authorization"] = "Bearer " + token
    req = urllib.request.Request(url, data=payload, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=30) as response:
            return response.status, response.read(), response.headers
    except urllib.error.HTTPError as error:
        return error.code, error.read(), error.headers


def same_site(site, value):
    parsed = urllib.parse.urlparse(value)
    expected = urllib.parse.urlparse(site)
    return parsed.scheme == expected.scheme and parsed.netloc == expected.netloc


def read_urls(path):
    value = Path(path).read_text(encoding="utf-8").strip()
    if value.startswith("["):
        urls = json.loads(value)
    else:
        urls = [
            line.strip()
            for line in value.splitlines()
            if line.strip() and not line.lstrip().startswith("#")
        ]
    if not isinstance(urls, list) or not urls or not all(
        isinstance(url, str) for url in urls
    ):
        raise ValueError("Provide a non-empty JSON array or one URL per line.")
    return urls


def write_state(path, state):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(state, indent=2), encoding="utf-8")
    os.chmod(path, 0o600)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--site", required=True)
    parser.add_argument("--urls", type=Path, help="JSON array or one URL per line.")
    parser.add_argument("--out", required=True, type=Path)
    parser.add_argument("--state", required=True, type=Path)
    parser.add_argument("--timeout", type=int, default=1200)
    args = parser.parse_args()

    site = args.site.rstrip("/")
    parsed = urllib.parse.urlparse(site)
    if parsed.scheme != "https" and not (
        parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost")
    ):
        raise ValueError("Use HTTPS, or a loopback URL for local development.")
    if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ("", "/"):
        raise ValueError("Site must be a bare origin without credentials.")

    if args.state.exists():
        state = json.loads(args.state.read_text(encoding="utf-8"))
    elif args.urls:
        urls = read_urls(args.urls)
        status, body, _ = request(
            site + "/v1/content-packages",
            "POST",
            {"urls": urls},
        )
        if status != 202:
            raise RuntimeError(f"Content package creation failed: HTTP {status}")
        created = json.loads(body)
        state = {
            "site": site,
            "id": created["id"],
            "packageToken": created["packageToken"],
            "statusUrl": created["statusUrl"],
        }
        write_state(args.state, state)
        print(f"Content package job: {state['id']}")
    else:
        raise ValueError("Provide --urls for a new job or an existing --state file.")

    if state.get("site") != site:
        raise ValueError("The state file belongs to a different site.")
    status_url = state["statusUrl"]
    if not same_site(site, status_url):
        raise ValueError("Refusing to send the package token to another site.")

    deadline = time.monotonic() + max(30, args.timeout)
    while time.monotonic() < deadline:
        status, body, _ = request(
            status_url,
            token=state["packageToken"],
        )
        if status != 200:
            raise RuntimeError(f"Content package status failed: HTTP {status}")
        current = json.loads(body)
        if current.get("state") == "failed":
            raise RuntimeError(
                "Content package retrieval did not complete: "
                + str(current.get("failureCode", "CONTENT_PACKAGE_FAILED"))
            )
        if current.get("state") == "complete" and current.get("packageUrl"):
            package_url = current["packageUrl"]
            if not same_site(site, package_url):
                raise ValueError("Refusing to download from another site.")
            status, payload, headers = request(
                package_url,
                token=state["packageToken"],
            )
            if status != 200:
                raise RuntimeError(f"Content package download failed: HTTP {status}")
            args.out.parent.mkdir(parents=True, exist_ok=True)
            args.out.write_bytes(payload)
            state["packageUrl"] = package_url
            state["downloadedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
            write_state(args.state, state)
            print(f"Saved content package: {args.out}")
            return
        time.sleep(min(5, max(1, current.get("pollAfterSeconds", 5))))
    raise TimeoutError("Timed out waiting for the content package.")


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(f"Content package error: {error}", file=sys.stderr)
        sys.exit(1)
