import argparse
import mimetypes
from pathlib import Path

import httpx


def upload_file(client: httpx.Client, base_url: str, bucket: str, local_file: Path, remote_path: str):
    content_type = mimetypes.guess_type(local_file.name)[0] or "application/octet-stream"
    with local_file.open("rb") as handle:
        response = client.post(
            f"{base_url}/storage/v1/object/{bucket}/{remote_path}",
            headers={
                "x-upsert": "true",
                "content-type": content_type,
            },
            content=handle.read(),
            timeout=120.0,
        )
    response.raise_for_status()


def main():
    parser = argparse.ArgumentParser(description="Upload optimized Bibliothek images to Supabase Storage")
    parser.add_argument("--input-dir", type=Path, required=True)
    parser.add_argument("--supabase-url", required=True)
    parser.add_argument("--service-key", required=True)
    parser.add_argument("--bucket", default="catalog-images")
    args = parser.parse_args()

    files = sorted(path for path in args.input_dir.rglob("*") if path.is_file())
    headers = {
        "Authorization": f"Bearer {args.service_key}",
        "apikey": args.service_key,
    }

    with httpx.Client(base_url=args.supabase_url.rstrip("/"), headers=headers) as client:
        for file_path in files:
            remote_path = file_path.relative_to(args.input_dir).as_posix()
            upload_file(client, args.supabase_url.rstrip("/"), args.bucket, file_path, remote_path)
            print(f"Uploaded {remote_path}")


if __name__ == "__main__":
    main()
