#!/usr/bin/env python3
"""Download John Pye invoices and products from Supabase to local JSON files."""

import asyncio
import json
import os
from datetime import datetime
from pathlib import Path

from dotenv import load_dotenv

load_dotenv()


async def main():
    import asyncpg

    output_dir = Path("johnpye_data")
    output_dir.mkdir(exist_ok=True)

    database_url = os.environ.get("DATABASE_URL")
    if not database_url:
        print("ERROR: DATABASE_URL not set in .env")
        return

    print("Connecting to Supabase...")
    pool = await asyncpg.create_pool(database_url, min_size=1, max_size=2)

    try:
        async with pool.acquire() as conn:
            # Fetch all invoices
            print("\nFetching invoices from database...")
            invoices = await conn.fetch("""
                SELECT * FROM johnpye_invoices
                ORDER BY created_at DESC
            """)
            print(f"Found {len(invoices)} invoices")

            # Convert to list of dicts with JSON-serializable dates
            invoices_list = []
            for inv in invoices:
                inv_dict = dict(inv)
                # Convert datetime/date objects to ISO strings
                for key, val in inv_dict.items():
                    if isinstance(val, datetime):
                        inv_dict[key] = val.isoformat()
                    elif hasattr(val, 'isoformat'):
                        inv_dict[key] = val.isoformat()
                    elif isinstance(val, (bytes, bytearray)):
                        inv_dict[key] = val.decode('utf-8')
                # Convert UUID to string
                if 'id' in inv_dict:
                    inv_dict['id'] = str(inv_dict['id'])
                invoices_list.append(inv_dict)

            # Save invoices
            invoices_file = output_dir / "invoices.json"
            with open(invoices_file, "w") as f:
                json.dump(invoices_list, f, indent=2, default=str)
            print(f"Saved invoices to {invoices_file}")

            # Fetch all lot items (products)
            print("\nFetching products/lot items from database...")
            products = await conn.fetch("""
                SELECT li.*, i.invoice_number, i.auction_name, i.created_at as invoice_date
                FROM johnpye_lot_items li
                JOIN johnpye_invoices i ON li.invoice_id = i.id
                ORDER BY i.created_at DESC, li.lot_number
            """)
            print(f"Found {len(products)} products")

            # Convert to list of dicts
            products_list = []
            for prod in products:
                prod_dict = dict(prod)
                for key, val in prod_dict.items():
                    if isinstance(val, datetime):
                        prod_dict[key] = val.isoformat()
                    elif hasattr(val, 'isoformat'):
                        prod_dict[key] = val.isoformat()
                # Convert UUIDs to strings
                if 'id' in prod_dict:
                    prod_dict['id'] = str(prod_dict['id'])
                if 'invoice_id' in prod_dict:
                    prod_dict['invoice_id'] = str(prod_dict['invoice_id'])
                products_list.append(prod_dict)

            # Save products
            products_file = output_dir / "products.json"
            with open(products_file, "w") as f:
                json.dump(products_list, f, indent=2, default=str)
            print(f"Saved products to {products_file}")

            # Summary stats
            total_value = sum(inv.get("grand_total_pence", 0) or 0 for inv in invoices_list)
            paid_count = sum(1 for inv in invoices_list if inv.get("invoice_status") == "paid")
            unpaid_count = len(invoices_list) - paid_count

            print(f"\n{'='*50}")
            print("DOWNLOAD COMPLETE")
            print(f"{'='*50}")
            print(f"Invoices: {len(invoices_list)} ({paid_count} paid, {unpaid_count} unpaid)")
            print(f"Products: {len(products_list)}")
            print(f"Total value: £{total_value/100:.2f}")
            print(f"\nFiles saved to: {output_dir.absolute()}")

    finally:
        await pool.close()


if __name__ == "__main__":
    asyncio.run(main())
