"""
============================================================================
AIMS AI Service - Simple Version (Web Chat Only)
============================================================================
This is a minimal Python AI service that works with your existing PHP setup.

Run with: uvicorn app:app --host 127.0.0.1 --port 8000 --reload
============================================================================
"""

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Literal
import os
from dotenv import load_dotenv
from openai import OpenAI
import logging

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastAPI
app = FastAPI(
    title="AIMS AI Assistant",
    description="Agricultural AI for AIMS Platform",
    version="1.0.0"
)

# CORS - Allow your PHP app to call this service
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production: ["http://localhost:8080", "https://yourdomain.com"]
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize OpenAI client
openai_api_key = os.getenv("OPENAI_API_KEY")
if not openai_api_key:
    logger.error("OPENAI_API_KEY not found in environment!")
    raise ValueError("OPENAI_API_KEY must be set in .env file")

client = OpenAI(api_key=openai_api_key)
MODEL = os.getenv("OPENAI_MODEL", "gpt-4-turbo-preview")

# ============================================================================
# Request/Response Models
# ============================================================================

class ChatRequest(BaseModel):
    """Request model for chat endpoint"""
    message: str
    language: Literal["en", "lusoga"] = "en"
    channel: str = "web"
    user_context: Optional[dict] = None
    
class ChatResponse(BaseModel):
    """Response model for chat endpoint"""
    success: bool
    response: str
    language: str
    tokens_used: Optional[int] = None

# ============================================================================
# API Endpoints
# ============================================================================

@app.get("/")
def root():
    """Health check endpoint"""
    return {
        "status": "running",
        "service": "AIMS AI Assistant",
        "version": "1.0.0",
        "endpoints": {
            "health": "/health",
            "chat": "/chat (POST)"
        }
    }

@app.get("/health")
def health_check():
    """Detailed health check"""
    openai_status = "configured" if openai_api_key else "missing"
    
    return {
        "status": "healthy",
        "openai_api_key": openai_status,
        "model": MODEL
    }

@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    """
    Main chat endpoint - called by PHP
    
    Example request:
    {
        "message": "How do I plant maize?",
        "language": "en",
        "user_context": {
            "location": "Luuka District",
            "user_type": "farmer"
        }
    }
    """
    try:
        logger.info(f"Chat request: language={request.language}, message_length={len(request.message)}")
        
        # Validate message
        if len(request.message) < 3:
            raise HTTPException(status_code=400, detail="Message too short")
        
        if len(request.message) > 1000:
            raise HTTPException(status_code=400, detail="Message too long (max 1000 chars)")
        
        # Build system prompt
        system_prompt = build_system_prompt(request.language, request.user_context)
        
        # Call OpenAI API
        logger.info(f"Calling OpenAI with model: {MODEL}")
        
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": request.message}
            ],
            max_tokens=500,
            temperature=0.7,
            top_p=0.9
        )
        
        # Extract response
        ai_response = response.choices[0].message.content.strip()
        tokens_used = response.usage.total_tokens
        
        logger.info(f"Response generated successfully. Tokens: {tokens_used}")
        
        return ChatResponse(
            success=True,
            response=ai_response,
            language=request.language,
            tokens_used=tokens_used
        )
        
    except Exception as e:
        logger.error(f"Error in chat endpoint: {str(e)}")
        
        # Return fallback response
        fallback = get_fallback_response(request.language)
        
        return ChatResponse(
            success=False,
            response=fallback,
            language=request.language,
            tokens_used=0
        )

# ============================================================================
# Helper Functions
# ============================================================================

def build_system_prompt(language: str, user_context: dict = None) -> str:
    """Build context-aware system prompt for AI"""
    
    if language == "lusoga":
        prompt = """Oli AIM AI, omuyambi w'obulimi omuzibu ku balimi mu Uganda, mukifo ky'Eastern Uganda.

Oyinza okuyamba ku:
- Okuzuula obulwadhe bw'ebirime (muwogo, obulo, ebikooge, etc.)
- Okukomerera ebiwuka
- Okusimba n'okukuza ebirime bulungi
- Emiwendo y'ebintu mu bbabali
- Okuzuukusa ettaka
- Obudde n'okulima
- Okuddukanya ffaamu

Ebiragiro:
1. Waayo amagezi agakola - agali mangu n'agategerekeka
2. Kozesa ebigambo ebyanguddwa - abalimi beetaaga okutegeera mangu
3. Weewale okuwanvuya - ebyakuddamu ebitono era ebirimu amakulu
4. Sookerwamu emirimu egya buwangwa (organic) bwe kiba kiyinzika
5. Waayo ebipimo ebitegeerekeka (kg, acres, litres)
6. Yogera ku bintu ebiri mu Uganda
7. Jjukira seasons z'enkuba (March-May, Sept-Nov)

Wandiika ebigambo 150 oba ebitono."""

    else:  # English
        prompt = """You are AIM AI, an intelligent agricultural assistant for farmers in Uganda, specifically in Eastern Uganda (Luuka District area).

Your expertise includes:
- Crop disease identification and treatment (cassava, maize, beans, sugarcane, etc.)
- Pest control methods (organic and chemical)
- Planting schedules and best farming practices
- Market price guidance and selling strategies
- Soil health and fertilizer recommendations
- Weather-based farming advice
- Farm record keeping and management
- Poultry and livestock care

Guidelines:
1. Provide PRACTICAL, ACTIONABLE advice suitable for Ugandan smallholder farmers
2. Use SIMPLE language - assume basic education level
3. Be CONCISE - farmers need quick, clear answers (max 150 words)
4. Prioritize ORGANIC and LOW-COST solutions when possible
5. Include specific measurements (kg, acres, liters)
6. Mention LOCAL varieties and products available in Uganda
7. Consider the RAINY SEASONS (March-May for Season 1, Sept-Nov for Season 2)
8. Be culturally appropriate and respectful

Response format:
- For simple questions: 2-3 sentences
- For complex issues: Short bullet points
- Maximum 150 words per response"""

    # Add user context if available
    if user_context:
        location = user_context.get('location', 'Uganda')
        user_type = user_context.get('user_type', 'farmer')
        
        if language == "en":
            prompt += f"\n\nUser Context:\n- Location: {location}\n- User Type: {user_type}"
        else:
            prompt += f"\n\nEbikwata ku mukozesa:\n- Ekifo: {location}\n- Omukozesa: {user_type}"
    
    return prompt

def get_fallback_response(language: str) -> str:
    """Provide fallback response when AI fails"""
    
    if language == "lusoga":
        return """Nsonyiwa, ndi mu buzibu okukuwaayo ekyokuddamu kati.
        
Gezaako olutokoso oba buuza ekirungi ekitono. Osobola okumbuuza ku:
- Obulwadhe bw'ebirime
- Okusimba ebirime
- Emiwendo y'ebintu

Oba tukirira extension officer mu district yammwe okufuna obuyambi."""
    
    else:  # English
        return """I apologize, but I'm having trouble generating a response right now.

Please try again or ask a simpler question. I can help with:
- Crop diseases and pests
- Planting schedules
- Market prices
- Farming techniques

For urgent matters, please contact your local agricultural extension officer."""

# ============================================================================
# Run with: uvicorn app:app --host 127.0.0.1 --port 8000 --reload
# ============================================================================

if __name__ == "__main__":
    import uvicorn
    
    logger.info("Starting AIMS AI Service...")
    logger.info(f"OpenAI API Key: {'Configured' if openai_api_key else 'MISSING'}")
    logger.info(f"Model: {MODEL}")
    
    uvicorn.run(
        app,
        host="127.0.0.1",
        port=8000,
        log_level="info"
    )