import os
import io
import json
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, Form, UploadFile, File, Request
from google import genai
from google.genai import types
from schemas.user import UserBase
from utils.jwt import verify_token

router = APIRouter(prefix="/quiz", tags=["quiz"])

GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
client = genai.Client(api_key=GOOGLE_API_KEY)
LLM_MODEL = 'gemini-2.5-flash'

async def get_quiz_user(request: Request):
    """
    Extracts and verifies the token from cookies or Authorization header.
    """
    token = None
    auth_header = request.headers.get("Authorization")
    if auth_header and auth_header.startswith("Bearer "):
        token = auth_header.split(" ")[1]
    
    if not token:
        token = request.cookies.get("access_token")
    
    if not token:
        raise HTTPException(status_code=401, detail="Not authenticated")
    
    payload = verify_token(token)
    if not payload:
        raise HTTPException(status_code=401, detail="Invalid token")
    
    return UserBase(email=payload.get("email"), name=payload.get("name"))

@router.post("/generate")
async def generate_quiz(
    request: Request,
    content_type: str = Form(...), # "text", "file"
    text: Optional[str] = Form(None),
    file: Optional[UploadFile] = File(None),
    current_user: UserBase = Depends(get_quiz_user)
):
    """
    Generates MCQs from provided text or file (PDF/Image).
    """
    try:
        contents = []
        
        if content_type == "text":
            if not text:
                raise HTTPException(status_code=400, detail="Text is required for text content type")
            contents.append(text)
        elif content_type == "file":
            if not file:
                raise HTTPException(status_code=400, detail="File is required for file content type")
            
            file_bytes = await file.read()
            uploaded_file = client.files.upload(
                file=io.BytesIO(file_bytes),
                config={'mime_type': file.content_type}
            )
            contents.append(uploaded_file)
        else:
             raise HTTPException(status_code=400, detail="Invalid content type")

        prompt = """
        Analyze the provided content and generate a set of Multiple Choice Questions (MCQs).
        The number of questions should depend on the length and depth of the content (e.g., 5-10 questions for short content, up to 20 for long content).
        
        Return the response STRICTLY as a JSON object with the following structure:
        {
            "questions": [
                {
                    "question": "The question text here?",
                    "options": [
                        { "text": "Option 1", "is_correct": false },
                        { "text": "Option 2", "is_correct": true },
                        { "text": "Option 3", "is_correct": false },
                        { "text": "Option 4", "is_correct": false }
                    ]
                }
            ]
        }
        
        Ensure:
        1. There are exactly 4 options per question.
        2. Exactly one option is marked as "is_correct": true.
        3. The questions cover the key points of the content.
        """
        
        contents.append(prompt)

        response = client.models.generate_content(
            model=LLM_MODEL,
            contents=contents,
            config=types.GenerateContentConfig(response_mime_type="application/json")
        )
        print(response)

        return json.loads(response.text)

    except Exception as e:
        print(f"Quiz Generation Error: {e}")
        raise HTTPException(status_code=500, detail=f"Quiz generation failed: {str(e)}")
