import os
from pathlib import Path
import sys
import time

import requests


def convert(session, source, output_dir):
    for attempt in range(5):
        # Reopen the file so a retry uploads the entire image again.
        with source.open("rb") as image:
            response = session.post(
                "https://svgme.app/api/v1/convert",
                files={"image": (source.name, image)},
                data={"colors": "4"},
                timeout=(10, 180),
            )
        with response:
            if response.ok:
                target = output_dir / f"{source.stem}.svg"
                target.write_bytes(response.content)
                print(f"Saved {target}")
                return
            if response.status_code != 429 and response.status_code < 500:
                response.raise_for_status()
            delay = float(response.headers.get("Retry-After", 5 * 2**attempt))
        if attempt < 4:
            time.sleep(delay)
    raise RuntimeError("gave up after 5 attempts")


def main():
    key = os.environ["SVGME_API_KEY"]
    output_dir = Path("svg")
    output_dir.mkdir(exist_ok=True)
    with requests.Session() as session:
        session.headers["Authorization"] = f"Bearer {key}"
        for source in sorted(Path("images").iterdir()):
            if not source.is_file() or source.suffix.lower() not in {".png", ".jpg", ".jpeg", ".webp"}:
                continue
            try:
                convert(session, source, output_dir)
            except (requests.RequestException, OSError, RuntimeError) as error:
                print(f"{source.name}: {error}", file=sys.stderr)


if __name__ == "__main__":
    main()
