import asyncio
import json
import time
import os
import random
from api.database import Database

async def main():
    # 1. Update npcs.json to add a test boss
    with open('gamedata/npcs.json', 'r') as f:
        data = json.load(f)
    if 'test_boss' not in data['npcs']:
        data['npcs']['test_boss'] = {
            "name": {"en": "Level 50 Test Boss", "es": "Jefe de Prueba Nivel 50"},
            "description": {"en": "A huge terrifying monster.", "es": "Un monstruo enorme y aterrador."},
            "emoji": "👹",
            "hp_min": 1000,
            "hp_max": 1500,
            "damage_min": 25,
            "damage_max": 45,
            "defense": 15,
            "xp_reward": 500,
            "loot_table": [],
            "flee_chance": 0.0,
            "status_inflict_chance": 0.5,
            "death_message": {"en": "The boss is defeated.", "es": "El jefe ha sido derrotado."}
        }
        with open('gamedata/npcs.json', 'w') as f:
            json.dump(data, f, indent=2)
        print("Added 'test_boss' to npcs.json")
        
    db = Database()
    await db.connect()
    
    # 2. Get Jocaru
    player = await db.fetch_one("SELECT * FROM characters WHERE name ILIKE 'Jocaru'")
    if not player:
        print("Player Jocaru not found!")
        await db.disconnect()
        return
        
    pid = player['id']
    ploc = player['location_id']
    
    # 3. Give items
    items_to_give = [
        ('reinforced_pack', 1),
        ('reinforced_bat', 1),
        ('knife', 1),
        ('first_aid_kit', 10),
        ('mystery_pills', 5),
        ('energy_bar', 10),
        ('molotov', 5)
    ]
    for item_id, qty in items_to_give:
        for _ in range(qty):
            from utils.game_helpers import generate_unique_item_stats
            from api.items import ITEMS_MANAGER
            item_def = ITEMS_MANAGER.get_item(item_id)
            if hasattr(item_def, 'durability') and item_def.durability:
                tier = item_def.tier if hasattr(item_def, 'tier') else 1
                stats = generate_unique_item_stats(item_id, item_def.durability, tier)
                uid = await db.create_unique_item(
                    item_id=item_id,
                    tier=tier,
                    durability=stats['durability'],
                    max_durability=stats['durability'],
                    stats=json.dumps(stats.get('stats', {}))
                )
                await db.execute(
                    "INSERT INTO inventory (character_id, item_id, quantity, unique_item_id) VALUES (:cid, :iid, 1, :uid)",
                    {"cid": pid, "iid": item_id, "uid": uid}
                )
            else:
                await db.execute(
                    "INSERT INTO inventory (character_id, item_id, quantity) VALUES (:cid, :iid, 1)",
                    {"cid": pid, "iid": item_id}
                )
    print("Granted test items and backpack.")
    
    # 4. Give XP to reach lvl 50 if needed
    await db.execute("UPDATE characters SET level = 50, xp = 50000, max_hp = 500, hp = 500, max_stamina = 200, stamina = 200 WHERE id = :pid", {"pid": pid})
    print("Buffed Jocaru to lvl 50 manually.")
        
    # 5. Spawn enemies at player's location
    now = time.time()
    despawn = now + 86400  # 1 day
    
    enemies_to_spawn = ['raider_scout'] * 5 + ['feral_dog'] * 5 + ['mutant_rat'] * 5 + ['test_boss'] * 2
    for eid in enemies_to_spawn:
        await db.execute(
            "INSERT INTO wandering_enemies (npc_id, location_id, spawn_timestamp, despawn_timestamp) VALUES (:nid, :loc, :start, :end)",
            {"nid": eid, "loc": ploc, "start": now, "end": despawn}
        )
    print(f"Spawned {len(enemies_to_spawn)} enemies at {ploc}")

    await db.disconnect()

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