import asyncio
import json
import time
import os
from 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!")
        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:
        await db.add_item_to_inventory(pid, item_id, qty)
    print("Granted test items and backpack.")
    
    # 4. Give XP to reach lvl 50 if needed
    # Level 50 is base + (50 * multiplier) ... the logic is in check_and_apply_level_up
    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())
