# import mysql.connector
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import os

from google import genai
from google.genai import types

app = FastAPI()

# CORS 설정
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 1. 클라이언트 설정 수정 (중요: v1alpha 지정)
# Thinking 모델은 실험적 기능이라 v1alpha 버전이 필요합니다.
client = genai.Client(
    api_key="AIzaSyCTlP3w-sndTqIidmNZITnsqD877xPdJdk", 
    http_options={'api_version': 'v1alpha'} 
)

class ChatRequest(BaseModel):
    message: str
    thinking_level: str = "OFF" # 주의: API 스펙에 따라 int가 필요할 수도 있음

@app.post("/goal-skill-t/api/chat")
async def chat_with_ai(request: ChatRequest):
    try:
        # 2. 모델명 수정: 날짜가 포함된 정확한 버전 사용 권장
        response = client.models.generate_content(
            model="gemini-2.0-flash-thinking-exp", 
            contents=request.message, 
            config=types.GenerateContentConfig(
                thinking_config=types.ThinkingConfig(
                    include_thoughts=True
                    # thinking_level 관련 에러가 나면 이 줄을 지우세요.
                    # thinking_level=request.thinking_level 
                )
            )
        )

        # 응답 처리 (안전장치 추가)
        thought_content = ""
        
        # 생각(Thought) 부분 추출 시도
        if hasattr(response, 'candidates') and response.candidates:
            for part in response.candidates[0].content.parts:
                if hasattr(part, 'thought') and part.thought: # SDK 버전에 따라 다를 수 있음
                    thought_content = part.thought
                    break
        
        # 만약 위 방식으로 안 잡히면 response.text만이라도 반환
        return {
            "status": "success",
            "thinking_process": thought_content,
            "answer": response.text
        }

    except Exception as e:
        print(f"Error: {e}") # 서버 콘솔에 에러 출력
        raise HTTPException(status_code=500, detail=str(e))