#!/usr/bin/env python3
"""
Spoolman Export Script for SimplyPrint
======================================
Exports all spools from a Spoolman instance as a JSON file
ready for import into SimplyPrint's Filament Manager.

Usage:
    python3 spoolman-export.py https://your-spoolman-url:7912
    python3 spoolman-export.py  # (will prompt for URL)

Output:
    spoolman-export.json in the current directory

Requirements:
    Python 3.6+ (no extra packages needed)
"""

import json
import sys
import urllib.request
import urllib.error


def fetch_json(url):
    """Fetch JSON from a URL."""
    req = urllib.request.Request(url, headers={
        "Accept": "application/json",
        "User-Agent": "SimplyPrint-SpoolmanExport/1.0",
    })
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.loads(resp.read().decode("utf-8"))


def flatten_spool(spool):
    """Flatten a Spoolman spool object into a flat dict for SimplyPrint import."""
    filament = spool.get("filament") or {}
    vendor = filament.get("vendor") or {}

    # Determine total weight: prefer initial_weight, fall back to filament.weight
    total_weight = spool.get("initial_weight") or filament.get("weight")

    return {
        "spoolman_spool_id": spool.get("id", ""),
        "brand": vendor.get("name", ""),
        "material": filament.get("material", ""),
        "filament_name": filament.get("name", ""),
        "color_hex": filament.get("color_hex", ""),
        "width": filament.get("diameter", 1.75),
        "total_weight_grams": total_weight,
        "remaining_weight_grams": spool.get("remaining_weight"),
        "location_name": spool.get("location", ""),
        "cost": spool.get("price"),
        "lot_nr": spool.get("lot_nr", ""),
        "custom_note": spool.get("comment", ""),
        "bought_at": spool.get("registered", ""),
    }


def main():
    # Get Spoolman URL
    if len(sys.argv) > 1:
        base_url = sys.argv[1].rstrip("/")
    else:
        base_url = input("Enter your Spoolman URL (e.g. http://localhost:7912): ").strip().rstrip("/")

    if not base_url:
        print("Error: No URL provided.")
        sys.exit(1)

    # Verify connection
    print(f"Connecting to {base_url}...")
    try:
        info = fetch_json(f"{base_url}/api/v1/info")
        print(f"Connected to Spoolman v{info.get('version', '?')}")
    except urllib.error.URLError as e:
        print(f"Error: Could not connect to {base_url}")
        print(f"  {e}")
        sys.exit(1)

    # Fetch all spools
    print("Fetching spools...")
    try:
        spools = fetch_json(f"{base_url}/api/v1/spool")
    except urllib.error.URLError as e:
        print(f"Error fetching spools: {e}")
        sys.exit(1)

    if not spools:
        print("No spools found.")
        sys.exit(0)

    # Filter out archived spools
    active_spools = [s for s in spools if not s.get("archived", False)]
    if len(active_spools) < len(spools):
        print(f"  Found {len(spools)} spools ({len(spools) - len(active_spools)} archived, skipped)")
    else:
        print(f"  Found {len(active_spools)} spools")

    # Flatten
    export_data = [flatten_spool(s) for s in active_spools]

    # Write output
    output_file = "spoolman-export.json"
    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(export_data, f, indent=2, ensure_ascii=False)

    print(f"\nExported {len(export_data)} spools to {output_file}")
    print("You can now import this file in SimplyPrint: Filament Manager > Import")


if __name__ == "__main__":
    main()
