"""
AtoLog Uploader (Python / Mac & Windows)
=========================================
How to use:
  1. Place this file in the same folder as atolog_upload.setting
  2. Drag and drop a PDF onto this script
     (Windows: associate .py with Python, then drag & drop)
     (Mac/Linux: python atolog_upload.py /path/to/file.pdf)

Requires: pip install requests
"""

import sys
import os
import requests

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SETTING_FILE = os.path.join(SCRIPT_DIR, "atolog_upload.setting")

# --- Read atolog_upload.setting ---
config = {}
try:
    with open(SETTING_FILE, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if "=" in line and not line.startswith("#"):
                k, v = line.split("=", 1)
                config[k.strip()] = v.strip()
except FileNotFoundError:
    print(f"Error: atolog_upload.setting not found at {SETTING_FILE}")
    input("Press Enter to close...")
    sys.exit(1)

domain  = config.get("DOMAIN", "")
api_key = config.get("API_KEY", "")

if not domain or not api_key:
    print("Error: DOMAIN or API_KEY not set in atolog_upload.setting")
    input("Press Enter to close...")
    sys.exit(1)

# --- Get file path (drag & drop or argument) ---
file_path = sys.argv[1] if len(sys.argv) > 1 else ""
if not file_path:
    print("Usage: drag and drop a PDF onto this script")
    print("  or:  python atolog_upload.py /path/to/file.pdf")
    input("Press Enter to close...")
    sys.exit(1)

# --- Upload ---
print(f"Uploading: {file_path}")
try:
    with open(file_path, "rb") as f:
        response = requests.post(
            f"https://{domain}/api/upload",
            headers={"X-API-Key": api_key},
            files={"file": f},
        )
    data = response.json()
    if response.ok:
        print("\nSuccess!")
        print(f"Share URL: {data.get('share_url')}")
    else:
        print(f"\nError: {data.get('error', 'Unknown error')}")
except FileNotFoundError:
    print(f"\nError: File not found: {file_path}")
except Exception as e:
    print(f"\nError: {e}")

input("\nPress Enter to close...")
