#! /usr/bin/env python3
import sys
import requests
import json
import argparse
import os
import tempfile
from pathlib import Path
import netrc

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("image", help="Image to upload")
    ap.add_argument("--no-compress", help="Don't compress the image", action="store_true")
    args = ap.parse_args()

    # Load the API key from the .netrc file
    if "catto.pictures" not in netrc.netrc().hosts:
        print("No catto.pictures entry in .netrc file")
        return 1
    login, account, password = netrc.netrc().authenticators("catto.pictures")
    
    # Parse the image to a path
    image_path = Path(args.image)

    # Ensure the file actually exists
    if not image_path.exists():
        print("File not found", file=sys.stderr)
        return 1

    # Compress the image to a temporary file
    with tempfile.NamedTemporaryFile(suffix=image_path.suffix) as temp:
        # Compress
        if not args.no_compress:
            os.system(f"convert {image_path} -quality 25% {temp.name}")
            image_path = Path(temp.name)

            # Strip all exif data
            os.system(f"exiftool -EXIF= {image_path}")
        
        # Upload the image
        with open(image_path, "rb") as f:
            r = requests.post(
                    "https://upload.catto.pictures", 
                    files={"image": (temp.name, f, f"image/{image_path.suffix[1:]}")},
                    headers={
                            "Authorization": password,
                            "Domain": "img.ewpratten.com",
                        }
                    )
            if r.status_code != 200:
                print(f"Error uploading image:\n{r.text}", file=sys.stderr)
                return 1
            print(json.loads(r.text)["url"])

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