#!/usr/bin/env python3
"""Export TLD prices from database to JSON file for backup/versioning."""
import asyncio
import json
import sys
from datetime import datetime
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy import select
from app.database import AsyncSessionLocal, init_db
from app.models.tld_price import TLDPrice


async def export_prices():
    """Export all TLD prices to JSON."""
    await init_db()
    
    async with AsyncSessionLocal() as db:
        result = await db.execute(select(TLDPrice).order_by(TLDPrice.tld))
        prices = result.scalars().all()
        
        data = {
            "exported_at": datetime.utcnow().isoformat(),
            "total_records": len(prices),
            "prices": [
                {
                    "tld": p.tld,
                    "registrar": p.registrar,
                    "registration_price": p.registration_price,
                    "renewal_price": p.renewal_price,
                    "transfer_price": p.transfer_price,
                    "currency": p.currency,
                    "promo_price": p.promo_price,
                    "recorded_at": p.recorded_at.isoformat() if p.recorded_at else None,
                }
                for p in prices
            ]
        }
        
        # Save to file
        output_path = Path(__file__).parent / "tld_prices_export.json"
        with open(output_path, "w") as f:
            json.dump(data, f, indent=2)
        
        print(f"Exported {len(prices)} TLD prices to {output_path}")
        return output_path


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

