from fastapi import APIRouter, HTTPException
from app.core.config import get_gemini_model
from app.models.report_db_module import save_daily_log, save_structured_diary, get_yesterday_data, update_yesterday_ai_feedback, get_all_daily_notes, update_boss_comment, get_today_data
from app.schemas.report_schemas import ReportAnalyzeRequest, SystemMessageRequest, YesterdayRequest
from pydantic import BaseModel
import json

class BossCommentRequest(BaseModel):
    session_id: str
    date: str
    boss_comment: str

router = APIRouter(
    prefix="/goal-skill-t/api",
    tags=["Report"]
)

@router.post("/Report/boss-comment")
async def save_boss_comment(request: BossCommentRequest):
    try:
        success = update_boss_comment(
            session_id=request.session_id,
            date=request.date,
            boss_comment=request.boss_comment
        )
        if success:
            return {"status": "success", "message": "フィードバックを保存しました。"}
        else:
            return {"status": "error", "message": "該当する日付の記録が見つかりませんでした。"}
    except Exception as e:
        print(f"Save Boss Comment Error: {e}")
        raise HTTPException(status_code=500, detail="サーバーエラーが発生しました。")

@router.get("/Report/all/{session_id}")
async def fetch_all_logs(session_id: str):
    try:
        # daily_note에서 최신순으로 가져옴
        rows = get_all_daily_notes(session_id)
        
        if not rows:
            return {"data": [], "message": "記録はありません。"} 
        
        response_data = []
        for row in rows:
            response_data.append({
                "date": str(row.get('date', '')),
                "learning": row.get('learning', ''),
                "mindset": row.get('today_mindset', ''),
                "advice": row.get('advice', ''),
                "boss_comment": row.get('boss_comment', '')
            })
        
        return {"data": response_data}
    except Exception as e:
        print(f"Fetch All Notes API Error: {e}")
        return {"data": [], "message": "データの読み取りに失敗しました。"}

@router.post("/Report/system-message")
async def get_system_message(request: SystemMessageRequest):
    try:
        client = get_gemini_model()
        
        # Setting Prompts by Message Type
        context_map = {
            "check_condition": "カリキュラムを作成する前に、現在のコンディション（日記）を入力するよう優しく促すメッセージ（日本語、1文、親しみやすい敬語）",
            "show_curriculum": "生成されたパーソナライズカリキュラムを提示し、確認してみるよう勧めるメッセージ（日本語、1文、自信のある口調）",
            "ask_feedback": "提示したカリキュラムが気に入ったか、感想を尋ねるメッセージ（日本語、1文）",
            "start_learning": "ユーザーがカリキュラムを承諾した際、力強く学習を始めようと励ますメッセージ（日本語、1文、情熱的な口調）"
        }
        
        target_context = context_map.get(request.message_type, "ユーザーへの自然な挨拶のメッセージ（日本語、1文）")

        prompt = f"""
        Task: Generate a natural, friendly system message in Japanese for an AI Tutor app.
        Context: {target_context}
        Constraint: Do not repeat the same phrase. Be creative but concise. Output only the Japanese text.
        """

        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=prompt,
            config={
                "temperature": 0.9
            }
        )
        
        return {"message": response.text.strip()}

    except Exception as e:
        print(f"System Message Error: {e}")
        # Returns default hard-coding message in case of error (safety)
        fallback_map = {
            "check_condition": "カリキュラムを作成する前に、今日のあなたの状態を把握しますね。",
            "show_curriculum": "今日のパーソナライズされたカリキュラムです。確認してみてください。",
            "ask_feedback": "今回のカリキュラムはいかがですか？",
            "start_learning": "いいですね。では、すぐにカリキュラムを始めましょう！"
        }
        return {"message": fallback_map.get(request.message_type, "")}


@router.post("/Report/analyze")
async def analyze_diary(request: ReportAnalyzeRequest):
    try:
        client = get_gemini_model()
        
        # [CASE 1] Diary mode (is_note = True)
        if request.is_note:
            # 1. Remove AI analysis/encouragement generation logic (reflect request)
            # Ai_comment is set to None because it will be added later
            ai_reply = None 

            # 2. Save DB (only save user input source, ai_comment is NULL)
            save_structured_diary(
                session_id=request.session_id,
                date=request.date,
                learning=request.learning,
                mindset=request.mindset,
                ai_comment=ai_reply 
            )
            
            # 3. Save bot logs (optional: only system message 'Save complete' is left)
            # save_daily_log(request.session_id, "bot", "日報を保存しました。")

            # 4. Front-end response
            # Instead of encouraging AI, we send a simple system message that the save is complete.
            return {"answer": "デイリーチェックを書いてくれてありがとう！さあ、『カリキュラム』ボタンを押して、実習を始めよう！"}

        # [CASE 2] General feedback/conversation mode (is_note = False)
        else:
            # Maintain existing conversation logic (if the user has entered it in the chat window)
            save_daily_log(request.session_id, "user", request.message)
            
            prompt = f"""
            User Feedback: "{request.message}"
            Task: Reply naturally in Japanese to the user's feedback.
            """
            
            response = client.models.generate_content(
                model="gemini-2.5-flash",
                contents=prompt
            )
            ai_reply = response.text.strip()
            
            save_daily_log(request.session_id, "bot", ai_reply)
            return {"answer": ai_reply}

    except Exception as e:
        print(f"Report Analyze Error: {e}")
        return {"answer": "サーバー通信中にエラーが発生しました。"}
    
@router.post("/Report/yesterday")
async def fetch_yesterday_log(request: YesterdayRequest):
    try:
        row = get_yesterday_data(request.session_id)
        
        # [Debugging]
        print(f"DEBUG ROW DATA: {row}") 
        
        if not row:
            return {"data": None, "message": "昨日の記録はありません。"} 
        
        ai_comment = row.get('ai_comment')
        advice = row.get('advice')
        
        # If either is empty, try creating
        if not ai_comment or not advice:
            try:
                client = get_gemini_model()
                
                # User Recordings
                user_learning = row.get('learning', 'なし')
                user_mindset = row.get('today_mindset', 'なし')
                
                # Creating Prompts
                prompt = f"""
                Task: Analyze the user's daily study log and provide feedback in JSON format.
                
                [User Log]
                Learning: {user_learning}
                Mindset: {user_mindset}
                
                [Requirements]
                1. "ai_comment": A warm, encouraging compliment about their learning or mindset (Japanese, polite tone).
                2. "advice": A brief, practical tip for better journaling or efficient studying based on the log (Japanese, polite tone).
                3. Output must be valid JSON only. No markdown formatting.
                
                Example format:
                {{"ai_comment": "...", "advice": "..."}}
                """

                # Call Gemini
                response = client.models.generate_content(
                    model="gemini-2.5-flash",
                    contents=prompt,
                    config={"response_mime_type": "application/json"} # JSON Forced (with model support)
                )
                
                # Result parsing
                import json
                generated_data = json.loads(response.text)
                
                new_ai_comment = generated_data.get("ai_comment", "素晴らしい取り組みですね！")
                new_advice = generated_data.get("advice", "継続は力なりです。")
                
                # Update DB
                update_yesterday_ai_feedback(row['id'], new_ai_comment, new_advice)
                
                # Reflects to current memory (that way, it can be seen immediately in return value)
                ai_comment = new_ai_comment
                advice = new_advice
                
            except Exception as e:
                print(f"AI Feedback Generation Error: {e}")
                # Show default values in case of creation failure (save DB or save default values)
                ai_comment = "素晴らしい進捗ですね！"
                advice = "今日もこの調子で頑張りましょう。"

        # Structured data return (for HTML rendering)
        # DB 컬럼명: date, learning, today_mindset, boss_comment
        response_data = {
            "date": str(row.get('date', '')), # String conversion safety for date objects
            "learning": row.get('learning', ''),
            "mindset": row.get('today_mindset', ''),
            "boss_comment": row.get('boss_comment', ''),
            "ai_comment": ai_comment,
            "advice": advice
        }
        
        return {"data": response_data}

    except Exception as e:
        print(f"Yesterday API Error: {e}")
        return {"data": None, "message": "データの読み込みに失敗しました。"}
    
    
@router.get("/Report/today-status/{session_id}")
async def fetch_today_status(session_id: str):
    try:
        # report_db_module.py에 이미 정의된 get_today_data 함수 사용
        row = get_today_data(session_id)
        
        if row and row.get('boss_comment'):
            return {
                "has_comment": True,
                "boss_comment": row.get('boss_comment'),
                "message": "今日のコメントがあります。"
            }
        else:
            return {
                "has_comment": False,
                "boss_comment": None,
                "message": "今日のコメントはまだありません。"
            }
    except Exception as e:
        print(f"Today Status API Error: {e}")
        return {"has_comment": False, "boss_comment": None}