import argparse
import json
import os
import sys
import time
from pathlib import Path
from tempfile import NamedTemporaryFile

import requests

JOBS = "https://api.lookscanned.io/v1/scan-jobs"
SCAN_CONFIG = {"colorspace": "gray", "resolution": 150, "rotate": 0.5}
POLL_SECONDS = 2
POLL_LIMIT_SECONDS = 180


def wait_for_download(session, job_id, auth):
    deadline = time.monotonic() + POLL_LIMIT_SECONDS
    while (remaining := deadline - time.monotonic()) > 0:
        response = session.get(f"{JOBS}/{job_id}", headers=auth, timeout=min(30, remaining))
        response.raise_for_status()
        job = response.json()
        status = job["status"]
        if status == "completed":
            return job["downloadURL"]
        if status not in {"created", "processing"}:
            raise RuntimeError(f"Scan job ended with status {status}")
        time.sleep(min(POLL_SECONDS, max(0, deadline - time.monotonic())))

    raise RuntimeError("Timed out waiting for the scan job")


def save_pdf(session, download_url, destination):
    with session.get(download_url, stream=True, timeout=60) as response:
        response.raise_for_status()
        file = NamedTemporaryFile(dir=destination.parent, suffix=".part", delete=False)
        temporary = Path(file.name)
        try:
            with file:
                for chunk in response.iter_content(chunk_size=128 * 1024):
                    file.write(chunk)
            temporary.replace(destination)
        finally:
            temporary.unlink(missing_ok=True)


def main():
    parser = argparse.ArgumentParser(description="Make scanned copies of a folder of PDFs.")
    parser.add_argument("source", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()

    token = os.environ.get("LOOKSCANNED_API_TOKEN")
    if not token:
        parser.error("Set LOOKSCANNED_API_TOKEN before running the script.")
    if not args.source.is_dir() or args.source.resolve() == args.output.resolve():
        parser.error("Choose an existing source directory and a separate output directory.")

    args.output.mkdir(parents=True, exist_ok=True)
    auth = {"Authorization": f"Bearer {token}"}
    converted = skipped = failed = 0

    with requests.Session() as session:
        for source in sorted(args.source.iterdir()):
            if not source.is_file() or source.suffix.lower() != ".pdf":
                continue
            destination = args.output / source.name
            if destination.is_file():
                skipped += 1
                continue

            job_id = None
            stage = "create"
            try:
                response = session.post(
                    JOBS, json={"config": SCAN_CONFIG}, headers=auth, timeout=30
                )
                response.raise_for_status()
                job = response.json()
                job_id = job["jobID"]

                stage = "upload"
                with source.open("rb") as pdf:
                    upload_headers = {
                        "Content-Type": "application/pdf",
                        "Content-Length": str(os.fstat(pdf.fileno()).st_size),
                    }
                    response = session.put(
                        job["uploadURL"], data=pdf, headers=upload_headers, timeout=120
                    )
                    response.raise_for_status()

                stage = "poll"
                download_url = wait_for_download(session, job_id, auth)
                stage = "download"
                save_pdf(session, download_url, destination)
            except (requests.RequestException, OSError, KeyError, RuntimeError) as error:
                if isinstance(error, requests.HTTPError) and error.response is not None:
                    reason = f"HTTP {error.response.status_code}"
                elif isinstance(error, RuntimeError):
                    reason = str(error)
                else:
                    reason = type(error).__name__
                failure = {"file": source.name, "jobID": job_id, "stage": stage, "reason": reason}
                with (args.output / "scan-failures.jsonl").open("a", encoding="utf-8") as log:
                    log.write(json.dumps(failure) + "\n")
                print(f"{source.name}: {stage} failed ({reason})", file=sys.stderr)
                failed += 1
            else:
                print(f"Saved {destination}")
                converted += 1

    print(f"{converted} converted, {skipped} already saved, {failed} failed")
    return int(failed > 0)


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