from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, List, Any
import json
import logging
from ..core.security import get_current_user


router = APIRouter(
    prefix="/api/npcs",
    tags=["npcs"],
    responses={404: {"description": "Not found"}},
)

logger = logging.getLogger(__name__)

from pathlib import Path

NPCS_DATA = {}

def init_router_dependencies():
    global NPCS_DATA
    try:
        # Use relative path consistent with Docker WORKDIR /app
        json_path = Path("./gamedata/static_npcs.json")
        with open(json_path, "r") as f:
            data = json.load(f)
            NPCS_DATA = data.get("static_npcs", {})
            logger.info(f"✅ Loaded {len(NPCS_DATA)} static NPCs")
    except Exception as e:
        logger.error(f"Failed to load static_npcs.json: {e}")
        NPCS_DATA = {}

@router.get("/location/{location_id}")
async def get_npcs_at_location(location_id: str):
    """Get all static NPCs at a location"""
    result = []
    for npc_id, npc_def in NPCS_DATA.items():
        if npc_def.get('location_id') == location_id:
            result.append(npc_def)
    return result

@router.get("/{npc_id}/dialog")
async def get_npc_dialog(npc_id: str, current_user: dict = Depends(get_current_user)):
    """Get dialog options for an NPC"""
    npc_def = NPCS_DATA.get(npc_id)
    if not npc_def:
        raise HTTPException(status_code=404, detail="NPC not found")
        
    dialog = npc_def.get('dialog', {})
    
    # Enrich with quest offers? 
    # Ideally checking available quests from quests.json where river_id == npc_id
    
    return dialog
