from fastapi import APIRouter, HTTPException
from app.models import curriculum_module
from app.schemas.curriculum_schema import StartCurriculumRequest, ChatCurriculumRequest, GetQuizRequest, CheckQuizRequest
from app.core.config import get_gemini_model
from google.genai import types
import json
import os
import logging
from fastapi.responses import FileResponse

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="/goal-skill-t/api/curriculum",
    tags=["Curriculum"]
)
file_router = APIRouter(
    prefix="/goal-skill-t/api/file",
    tags=["Files"]
)

SYSTEM_PROMPT = """
あなたは学習者の「親しい友人（Best Friend）」です。
以下のルールを絶対に守ってください：
1. **言語**: 日本語のみ使用。
2. **口調**: 絶対に敬語（〜です、〜ます）を使わないこと。「〜だよ」「〜じゃん」「〜だね」といった、仲の良い友達と話す「タメ口」を使うこと。
3. **態度**: 明るく、ポジティブに、絵文字（🔥, ✨, 💪, 😂など）を多用して会話すること。
4. **役割**: 先生ではなく、一緒に走るパートナーとして振る舞うこと。
"""

@router.post("/start")
async def start_curriculum(request: StartCurriculumRequest):
    try:
        session_id = "sess_1yjx2z3791770012471967" # 하드코딩
        
        # 1. 진도 확인
        progress = curriculum_module.get_user_progress(session_id)
        if not progress:
             return {"status": "error", "message": "進捗データが見つかりません。"}
        
        current_day = progress['current_day']
        status = progress['status']
        
        # 0(진행중)이 아니면 시작 안 함 (이미 완료했거나 등등) -> 여기서는 0일때만 로직 수행
        if status != 0:
            return {"status": "completed", "message": "本日の学習は既に完了しています。"}

        # 2. 데이터 조회 (어제 회고, 오늘 아이템)
        prev_data = curriculum_module.get_previous_feedback(session_id, current_day)
        today_item = curriculum_module.get_today_item_info(session_id, current_day)
        
        if not today_item:
             return {"status": "error", "message": "本日のカリキュラムが見つかりません。"}

        # 3. 프롬프트 구성
        item_name = today_item['name']
        prev_summary = prev_data['summary_content'] if prev_data else "なし"
        prev_feedback = prev_data['ai_feedback'] if prev_data else "なし"
        prev_praise = prev_data['praise_content'] if prev_data else "なし"
        
        prompt = f"""
            今日は学習 {current_day}日目だね！
            今日の学習テーマは「{item_name}」だよ。
            
            [昨日の振り返り]
            - 学習内容: {prev_summary}
            - AIフィードバック: {prev_feedback}
            - 称賛: {prev_praise}
            
            これらを踏まえて、今日の学習を始めるユーザーに、日本語で「親しい友人」として応援メッセージを送って！
            
            [制約事項]
            1. **敬語禁止**：友達と話すようにタメ口で。
            2. 内容：昨日の頑張りを褒めつつ、今日のテーマ「{item_name}」がどれだけ面白いか、ワクワクするように伝えて。
            3. 長さ：長すぎず、パッと読んで元気が出るように。絵文字も使って！
            """
        
        client = get_gemini_model()
        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=[types.Content(role="user", parts=[types.Part(text=prompt)])],
            config={"system_instruction": SYSTEM_PROMPT}
        )
        
        return {
            "status": "start",
            "message": response.text,
            "current_day": current_day,
            "item_id": today_item['item_id']
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/chat")
async def chat_curriculum(request: ChatCurriculumRequest):
    try:
        client = get_gemini_model()
        
        # 1. 시작 단계 (긍정/부정 판별)
        if request.current_step == 'START':
            prompt = f"""
            ユーザーの発言: "{request.user_message}"
            
            この発言が「ポジティブ(やる気がある)」か「ネガティブ(やる気がない・不安)」か判定してください。
            
            もし「ネガティブ」なら、「目標を達成するためには、今やるしかない！」というニュアンスの厳しめの応援メッセージを作成してください。
            もし「ポジティブ」なら、「その意気だ！必ず目標は達成できる！」というニュアンスの強い称賛メッセージを作成してください。
            
            出力フォーマット(JSON):
            {{
                "sentiment": "POSITIVE" or "NEGATIVE",
                "message": "作成したメッセージ"
            }}
            """
            response = client.models.generate_content(
                model="gemini-2.5-flash",
                contents=[types.Content(role="user", parts=[types.Part(text=prompt)])],
                config={"response_mime_type": "application/json"}
            )
            return json.loads(response.text)

        # 2. 유튜브 완료 확인
        elif request.current_step == 'YOUTUBE':
            # 2-1. 사용자 발언 분석 (완료했는지)
            prompt_check = f"""
            ユーザーの発言: "{request.user_message}"
            ユーザーが「動画を見終わった」「勉強が終わった」と言っているか判定してください。
            JSONで {{"is_finished": true}} または {{"is_finished": false}} を返してください。
            """
            response = client.models.generate_content(
                model="gemini-2.5-flash",
                contents=[types.Content(role="user", parts=[types.Part(text=prompt_check)])],
                config={"response_mime_type": "application/json"}
            )
            result = json.loads(response.text)
            
            if result['is_finished']:
                session_id = "sess_1yjx2z3791770012471967"
                
                # =================================================================
                # [수정] item_id가 None일 경우, DB에서 현재 진도를 조회하여 자동 탐지
                # =================================================================
                target_item_id = request.item_id
                
                if target_item_id is None:
                    print("!!! item_id is Missing -> Auto-detecting from Progress !!!")
                    # 1. 현재 몇 일차인지 확인
                    progress = curriculum_module.get_user_progress(session_id)
                    if progress:
                        current_day = progress['current_day']
                        # 2. 해당 날짜의 대표 아이템 ID 하나만 가져오기
                        today_info = curriculum_module.get_today_item_info(session_id, current_day)
                        if today_info:
                            target_item_id = today_info['item_id']
                            print(f"   -> Auto-detected item_id: {target_item_id}")

                # =================================================================
                # 1. 데이터 조회 (탐지된 target_item_id 사용)
                # =================================================================
                if target_item_id:
                    daily_items, _ = curriculum_module.get_daily_items_and_resources(session_id, target_item_id)
                else:
                    daily_items = [] # 여전히 못 찾았으면 빈 리스트

                print(f"============== [DEBUG LOG] ==============")
                print(f"1. Target item_id: {target_item_id}")
                print(f"2. Daily Items Found: {len(daily_items) if daily_items else 0}")

                # PPT 파일이 저장된 실제 경로
                # PPT_BASE_DIR = "/home/air/goalskill_t/back/PPT/"
                PPT_BASE_DIR = "/home/air/goalskill_t/front/PPT/"
                
                valid_ppts = []
                valid_item_names = []

                if daily_items:
                    for item in daily_items:
                        item_id = item['item_id']
                        file_name = f"item_{item_id}.pptx"
                        file_path = os.path.join(PPT_BASE_DIR, file_name)
                        
                        print(f"3. Checking PPT: {file_name}")
                        
                        # [핵심] 파일이 실제로 존재할 때만 리스트에 추가
                        if os.path.exists(file_path):
                            print(f"   -> FOUND")
                            valid_ppts.append({
                                "item_id": item_id,
                                "name": item['name'],
                                "url": f"https://air.sekoaischool.com/goal-skill-t/api/file/ppt/{file_name}" 
                            })
                            valid_item_names.append(item['name'])
                        else:
                            print(f"   -> NOT FOUND")
                
                print(f"=========================================")

                # =================================================================
                # 2. AI 프롬프트 구성
                # =================================================================
                if not valid_ppts:
                    # PPT가 하나도 없으면 바로 퀴즈로 넘어가거나 안내
                     return {"is_finished": True, "message": "今回はPPT資料はないみたい！次はクイズに進もうか！", "ppts": []}

                ppt_topic_str = "」と「".join(valid_item_names)
                
                ppt_prompt = f"""
                状況: あなたはユーザーの親しい友人（Best Friend）です。
                タスク: 学習内容「{ppt_topic_str}」をまとめたPPT資料（合計 {len(valid_ppts)}つ）を渡します。
                
                [制約事項]
                1. **口調**: 完全なタメ口（〜だよ、〜作ったよ）。敬語禁止。
                2. **出力**: 「パターン1」などの選択肢は絶対に出さないこと。**ユーザーに送る最終的なメッセージを1つだけ**出力すること。
                3. **内容**: 「もっと理解深まるようにPPT作ったから見てみて！」という感じで明るく勧めること。
                4. **URL禁止**: メッセージ内にURLやファイル名は書かないこと。（システムが別途表示するため）
                """
                
                ppt_msg_response = client.models.generate_content(
                    model="gemini-2.5-flash",
                    contents=[types.Content(role="user", parts=[types.Part(text=ppt_prompt)])]
                )
                
                return {
                    "is_finished": True, 
                    "message": ppt_msg_response.text,
                    "ppts": valid_ppts 
                }
                
            else:
                return {"is_finished": False, "message": "動画を見終わったら教えてね！待ってるよ〜"}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/resources")
async def get_resources(request: GetQuizRequest):
    try:
        session_id = "sess_1yjx2z3791770012471967"
        
        daily_items, resources = curriculum_module.get_daily_items_and_resources(session_id, request.item_id)
        
        if not daily_items:
             raise HTTPException(status_code=404, detail="Schedule not found")

        topic_names = "」と「".join([item['name'] for item in daily_items])
        
        logger.info(f"Today's Topics: {topic_names}")
        logger.info(f"Total Resources Found: {len(resources)}")

        client = get_gemini_model()
        
        intro_prompt = f"""
        状況: あなたはユーザーの親しい友人（Best Friend）です。
        今日の学習テーマは「{topic_names}」だね！
        
        これらに関連するYouTube動画（合計 {len(resources)}本）を見つけたので、ユーザーに紹介して。
        特に「条件分岐」や「算術演算」など、動画の内容に合わせて興味を引くように話して。

        [制約事項]
        1. **口調**: 完全に「タメ口」で（〜だよ、〜じゃん）。
        2. **URL禁止**: URLや(リンク)と書かないこと。
        3. **内容**: 今日学ぶ複数のトピック（計算や条件分岐など）をうまく繋げて、「これ見たら今日の勉強バッチリ！」という感じで勧めて。
        """

        intro_msg_response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=[types.Content(role="user", parts=[types.Part(text=intro_prompt)])]
        )
        
        return {
            "message": intro_msg_response.text,
            "resources": resources  # 이제 18번 영상 정보가 포함되어 반환됩니다!
        }

    except Exception as e:
        logger.error(str(e))
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/quiz")
async def get_quiz(request: GetQuizRequest):
    try:
        # 문제 조회
        problem = curriculum_module.get_quiz_problem(request.item_id, request.q_num)
        if not problem:
             raise HTTPException(status_code=404, detail="問題が見つかりません。")
        return problem
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/quiz/check")
async def check_quiz(request: CheckQuizRequest):
    try:
        client = get_gemini_model()
        
        prompt = f"""
        問題: {request.question_text}
        ユーザーの回答: {request.user_answer}
        
        この回答が正解かどうか判定してください。
        正解なら「正解！さすがだね！」、不正解なら「惜しい！不正解だよ」のような親しい口調で解説を書いてください。敬語は使わないでください。
        """
        
        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=[types.Content(role="user", parts=[types.Part(text=prompt)])]
        )
        
        return {"result_message": response.text}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    

@file_router.get("/ppt/{file_name}")
async def get_ppt_file(file_name: str):
    """
    프론트엔드 URL: /goal-skill-t/api/file/ppt/item_18.pptx
    실제 서버 경로: /home/air/goalskill_t/back/PPT/item_18.pptx
    """
    # 1. 실제 파일이 있는 서버 내부 경로
    base_dir = "/home/air/goalskill_t/back/PPT/"
    file_path = os.path.join(base_dir, file_name)
    
    # 2. 파일이 진짜 있는지 확인하고 전송
    if os.path.exists(file_path):
        return FileResponse(
            path=file_path, 
            filename=file_name, 
            # 브라우저가 PPT임을 알 수 있게 미디어 타입 지정
            media_type='application/vnd.openxmlformats-officedocument.presentationml.presentation'
        )
    else:
        # 파일이 없으면 404 에러
        raise HTTPException(status_code=404, detail="File not found on server")