from fastapi import APIRouter, Depends, HTTPException, Query, Path
from typing import List, Optional
from sqlalchemy.orm import Session

from src.utils.db import get_db
from src.marketing.apps.persona import controller, schema

router = APIRouter()


@router.post("/generate", response_model=schema.PersonaGenerationResponse)
def generate_persona(
    request: schema.PersonaGenerationRequest,
    db: Session = Depends(get_db)
):
    """
    Generate persona for a store based on post data using Azure LLM.
    
    Analyzes social media posts to identify:
    - Industry
    - Audience type
    - Brand voice
    - Content style
    """
    try:
        persona_controller = controller.PersonaController(db)
        result = persona_controller.generate_persona(
            store_id=request.store_id,
            branch_id=request.branch_id
        )
        
        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)
        
        return result
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error generating persona: {str(e)}")


@router.get("/store/{store_id}", response_model=schema.StorePersonaResponse)
def get_store_persona(
    store_id: int = Path(..., description="ID of the store"),
    branch_id: Optional[int] = Query(None, description="Optional branch ID"),
    db: Session = Depends(get_db)
):
    """
    Get existing persona for a store.
    
    Returns the current brand persona analysis including:
    industry, audience type, brand voice, and content style.
    """
    try:
        persona_controller = controller.PersonaController(db)
        persona = persona_controller.get_persona(store_id, branch_id)
        
        if not persona:
            raise HTTPException(status_code=404, detail="Persona not found for this store")
        
        return persona
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error retrieving persona: {str(e)}")


@router.get("/store/{store_id}/list", response_model=List[schema.StorePersonaResponse])
def list_store_personas(
    store_id: int = Path(..., description="ID of the store"),
    db: Session = Depends(get_db)
):
    """
    List all personas for a store (including branch-specific ones).
    
    Returns a list of all personas associated with the store,
    including main store persona and any branch-specific personas.
    """
    try:
        persona_controller = controller.PersonaController(db)
        return persona_controller.list_store_personas(store_id)
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error listing personas: {str(e)}")


@router.put("/store/{store_id}", response_model=schema.StorePersonaResponse)
def update_persona(
    store_id: int = Path(..., description="ID of the store"),
    branch_id: Optional[int] = Query(None, description="Optional branch ID"),
    update_data: schema.PersonaUpdateRequest = None,
    db: Session = Depends(get_db)
):
    """
    Update existing persona for a store.
    
    Allows manual updates to industry, audience type, brand voice,
    and content style. Only provided fields will be updated.
    """
    try:
        persona_controller = controller.PersonaController(db)
        persona = persona_controller.update_persona(store_id, branch_id, update_data)
        
        if not persona:
            raise HTTPException(status_code=404, detail="Persona not found for this store")
        
        return persona
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error updating persona: {str(e)}")


@router.delete("/store/{store_id}")
def delete_persona(
    store_id: int = Path(..., description="ID of the store"),
    branch_id: Optional[int] = Query(None, description="Optional branch ID"),
    db: Session = Depends(get_db)
):
    """
    Delete persona for a store.
    
    Soft deletes the persona (sets is_active to false).
    """
    try:
        persona_controller = controller.PersonaController(db)
        success = persona_controller.delete_persona(store_id, branch_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="Persona not found for this store")
        
        return {"success": True, "message": "Persona deleted successfully"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error deleting persona: {str(e)}")


@router.get("/health")
def persona_health_check():
    """
    Health check endpoint for persona service.
    
    Returns basic service status information.
    """
    return {
        "status": "healthy",
        "service": "LLM Persona Analysis",
        "version": "2.0.0",
        "description": "Azure LLM-powered store brand persona generation"
    }
