#!/usr/bin/env python3
"""
Script to import TOKEN_SETS from config.py to Laravel database.
Run this after migrating the database and seeding the initial tokens.

Usage:
    python scripts/import_tokens_to_db.py

Environment variables:
    LARAVEL_API_URL - Laravel API URL (default: http://127.0.0.1:8000)
    ADMIN_API_KEY - Admin API key (default: locket-gold-secret-2024)
"""

import os
import sys
import asyncio
import aiohttp

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.config import TOKEN_SETS_CONFIG


async def import_tokens():
    api_url = os.environ.get('LARAVEL_API_URL', 'http://127.0.0.1:8000')
    admin_key = os.environ.get('ADMIN_API_KEY', 'locket-gold-secret-2024')

    # Create JSON import data
    import_data = {
        "TOKEN_SETS": []
    }

    for token in TOKEN_SETS_CONFIG:
        import_data["TOKEN_SETS"].append({
            "name": token.get("name", "Imported Token"),
            "fetch_token": token.get("fetch_token", ""),
            "app_transaction": token.get("app_transaction", ""),
            "hash_params": token.get("hash_params"),
            "hash_headers": token.get("hash_headers"),
            "is_sandbox": token.get("is_sandbox", False),
            "cooldown_seconds": token.get("cooldown_seconds", 15),
        })

    print(f"Importing {len(import_data['TOKEN_SETS'])} tokens to database...")
    print(f"API URL: {api_url}")

    url = f"{api_url}/api/token-sets/import"
    headers = {
        'Content-Type': 'application/json',
        'X-Admin-Key': admin_key
    }

    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=import_data, headers=headers) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    print(f"Success: {data}")
                else:
                    text = await resp.text()
                    print(f"Error: Status {resp.status}")
                    print(f"Response: {text}")
    except Exception as e:
        print(f"Connection error: {e}")
        print("\nMake sure Laravel is running and the database is migrated.")
        print("Run: php artisan migrate")


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