"""
FastAPI Server - Real-time Search API

Server này:
- Load & build index KHI STARTUP (1 lần duy nhất)
- Cung cấp API endpoint /api/search
- Support realtime search với debounce ở frontend
"""

import sys
sys.path.append('src')

from fastapi import FastAPI, Query, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from typing import List, Dict, Optional
import time

from api.search_service import get_search_service


# ============================================================
# REQUEST/RESPONSE MODELS
# ============================================================

class SearchRequest(BaseModel):
    """Request body cho POST /api/search"""
    text: str = Field(..., description="Search query text", min_length=1)
    limit: Optional[int] = Field(20, description="Maximum results", ge=1, le=100)
    
    class Config:
        json_schema_extra = {
            "example": {
                "text": "làm sạch",
                "limit": 20
            }
        }


class SearchResponse(BaseModel):
    """Response body cho POST /api/search"""
    query: str
    total: int
    time_ms: float
    results: List[Dict]


# ============================================================
# KHỞI TẠO FASTAPI APP
# ============================================================

app = FastAPI(
    title="Work Search API",
    description="Real-time search API cho công việc làm sạch",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS - Cho phép frontend gọi API
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Production: thay bằng domain cụ thể
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ============================================================
# STARTUP EVENT - XÂY CÂY TRIE KHI KHỞI ĐỘNG SERVER
# ============================================================

@app.on_event("startup")
async def startup_event():
    """
    Event chạy KHI SERVER STARTUP
    
    ĐÂY LÀ NƠI XÂY CÂY TRIE!
    - Chỉ chạy 1 lần duy nhất
    - Load data & build index
    - Sau đó share cho tất cả requests
    """
    print("\n" + "🌟" * 40)
    print("FASTAPI SERVER STARTING...")
    print("🌟" * 40)
    
    # Get service instance
    service = get_search_service()
    
    # Initialize (load data + build trie)
    try:
        service.initialize(
            data_path="data/unique_work_contents.json",
            max_results=20
        )
        print("✅ Search service ready!")
    except Exception as e:
        print(f"❌ Failed to initialize search service: {e}")
        raise


@app.on_event("shutdown")
async def shutdown_event():
    """Event khi server shutdown"""
    print("\n👋 Server shutting down...")


# ============================================================
# API ENDPOINTS
# ============================================================

@app.get("/")
async def root():
    """
    Homepage - Kiểm tra server có hoạt động không
    """
    return {
        "message": "Work Search API is running!",
        "version": "1.0.0",
        "docs": "/docs",
        "endpoints": {
            "search": "/api/search?q=<query>",
            "stats": "/api/stats"
        }
    }


@app.post("/api/search", response_model=SearchResponse)
async def search_post(request: SearchRequest):
    """
    ENDPOINT CHÍNH - REALTIME SEARCH (POST với JSON body)
    
    Cách hoạt động:
    ---------------
    1. Frontend gọi API này mỗi khi user GÕ (với debounce 150ms)
    2. Backend search trong Trie đã build sẵn
    3. Trả về kết quả trong < 5ms
    
    Request Body (JSON):
    -------------------
    {
        "text": "làm sạch",
        "limit": 20
    }
    
    Returns:
    --------
    {
        "query": "làm sạch",
        "total": 15,
        "time_ms": 2.5,
        "results": [
            {
                "id": 0,
                "text": "Làm sạch nhà vệ sinh",
                "score": 1.0
            },
            ...
        ]
    }
    
    Example (Postman):
    ------------------
    POST http://localhost:8000/api/search
    Content-Type: application/json
    
    Body:
    {
        "text": "làm sạch",
        "limit": 20
    }
    """
    service = get_search_service()
    
    # Kiểm tra service ready
    if not service.is_ready:
        raise HTTPException(
            status_code=503,
            detail="Search service not ready"
        )
    
    # Đo thời gian
    start_time = time.time()
    
    try:
        # SEARCH - Đây là bước chính!
        results = service.search(query=request.text, limit=request.limit)
        
        elapsed_ms = (time.time() - start_time) * 1000
        
        return SearchResponse(
            query=request.text,
            total=len(results),
            time_ms=round(elapsed_ms, 2),
            results=results
        )
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Search error: {str(e)}"
        )


@app.get("/api/document/{doc_id}")
async def get_document(doc_id: int):
    """
    Lấy document theo ID
    
    Parameters:
    -----------
    - doc_id: ID của document
    
    Returns:
    --------
    {
        "id": 0,
        "text": "Làm sạch nhà vệ sinh"
    }
    """
    service = get_search_service()
    
    doc = service.get_document(doc_id)
    
    if doc is None:
        raise HTTPException(
            status_code=404,
            detail=f"Document {doc_id} not found"
        )
    
    return {
        "id": doc_id,
        "text": doc
    }


@app.get("/api/stats")
async def get_stats():
    """
    Lấy thống kê về search engine
    
    Returns:
    --------
    {
        "status": "ready",
        "documents": 1234,
        "trie_nodes": 45678,
        "max_results": 20,
        "features": [...]
    }
    """
    service = get_search_service()
    return service.get_stats()


@app.get("/health")
async def health_check():
    """
    Health check - Cho monitoring
    """
    service = get_search_service()
    
    return {
        "status": "healthy" if service.is_ready else "not_ready",
        "timestamp": time.time()
    }


# ============================================================
# MAIN - CHẠY SERVER
# ============================================================

if __name__ == "__main__":
    import uvicorn
    
    print("\n" + "=" * 80)
    print("🚀 STARTING WORK SEARCH API SERVER")
    print("=" * 80)
    print("\n📍 Endpoints:")
    print("   - API:    http://localhost:8000/api/search?q=<query>")
    print("   - Docs:   http://localhost:8000/docs")
    print("   - Health: http://localhost:8000/health")
    print("\n" + "=" * 80 + "\n")
    
    # Chạy server
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        log_level="info"
    )
