"""Queue Google organic tasks and write one terminal job per line to stdout."""

import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen

API = "https://kieapi.com/v1/serp"


def request_job(path, token, body=None, key=None):
    headers = {"Authorization": f"Bearer {token}"}
    data = None
    expected = 200
    if body is not None:
        headers.update({"Content-Type": "application/json", "Idempotency-Key": key})
        data = json.dumps(body).encode()
        expected = 202
    request = Request(API + path, headers=headers, data=data)
    try:
        with urlopen(request, timeout=30) as response:
            if response.status != expected:
                raise ValueError(f"{path} returned {response.status}, expected {expected}")
            return json.load(response)["job"]
    except HTTPError as exc:
        message = exc.read().decode(errors="replace")
        raise RuntimeError(f"{path}: HTTP {exc.code}: {message}") from exc


def is_pending(job):
    if job["status"] in ("queued", "running"):
        return True
    return (job["status"] == "failed"
            and (job.get("error") or {}).get("retryable", False)
            and job["attempt_count"] < job["max_attempts"])


def run(keywords, country, run_id, token):
    pending = {}
    for keyword in keywords:
        body = {"q": keyword, "country": country}
        identity = json.dumps([run_id, body], sort_keys=True).encode()
        key = "serp-batch-" + hashlib.sha256(identity).hexdigest()
        job = request_job("/google/organic/tasks", token, body, key)
        pending[job["id"]] = job

    deadline = time.monotonic() + 600
    failed = False
    while pending:
        for task_id, job in list(pending.items()):
            if is_pending(job):
                job = request_job(f"/tasks/{task_id}", token)
            if is_pending(job):
                pending[task_id] = job
            elif job["status"] in ("completed", "failed"):
                print(json.dumps({"run_id": run_id, "job": job}), flush=True)
                if job["status"] == "failed":
                    failed = True
                del pending[task_id]
            else:
                raise ValueError(f"Unknown task status for {task_id}: {job['status']}")
        if pending:
            if time.monotonic() >= deadline:
                raise TimeoutError("Polling timed out. Rerun with the same run ID and inputs.")
            time.sleep(5)
    return int(failed)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("file", type=Path, help="UTF-8 file with one keyword per line")
    parser.add_argument("--country", default="US")
    parser.add_argument("--run-id", required=True, help="Reuse this ID when resuming a run")
    args = parser.parse_args()
    token = os.environ.get("SPIDEYDATA_API_KEY")
    if not token:
        parser.error("Set SPIDEYDATA_API_KEY first")
    lines = args.file.read_text(encoding="utf-8-sig").splitlines()
    keywords = list(dict.fromkeys(line.strip() for line in lines if line.strip()))
    if not keywords or any(len(keyword) > 512 for keyword in keywords):
        parser.error("Supply at least one keyword; each must fit in 512 characters")
    return run(keywords, args.country.upper(), args.run_id, token)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, ValueError, RuntimeError) as error:
        sys.exit(str(error))
