from fastapi import APIRouter, HTTPException
from app.models import progress_module
from app.schemas.progress_schema import StartCurriculumRequest
from app.core.config import get_gemini_model
from fastapi.responses import HTMLResponse
from google.genai import types
import json
import os
import logging
from fastapi.responses import FileResponse
import glob

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="/goalskill-sales/api/progress",
    tags=["Progress"]
)
file_router = APIRouter(
    prefix="/goalskill-sales/api/file",
    tags=["Files"]
)

# ... SYSTEM_PROMPT 생략 ...

@router.get("/chart-view/{session_id}")
async def get_chart_page(session_id: str):
    # 1. 프로젝트 루트 경로 찾기
    # 현재 파일 위치: back/app/routers/progress_router.py
    current_file_dir = os.path.dirname(os.path.abspath(__file__)) # .../back/app/routers
    app_dir = os.path.dirname(current_file_dir)                   # .../back/app
    back_dir = os.path.dirname(app_dir)                           # .../back
    root_dir = os.path.dirname(back_dir)                          # .../ (Project Root)

    # 2. ★ 경로 수정: front/components/dashboard.html
    # 이제 root_dir이 프로젝트 최상위이므로, 여기서 front로 들어갑니다.
    file_path = os.path.join(root_dir, "front", "components", "dashboard.html")
    
    if os.path.exists(file_path):
        return FileResponse(file_path)
    
    # 파일을 못 찾았을 때 로그 (터미널에서 확인 가능)
    logger.error(f"Dashboard file not found at: {file_path}") 
    return {"error": "Dashboard file not found"}

@router.get("/chart-data/{session_id}")
async def get_chart_data_api(session_id: str):
    """
    DB에서 실제 데이터를 조회하여 JSON으로 반환
    """
    try:
        # progress_module은 이미 P_ 및 T_ 테이블 로직이 구현되어 있다고 가정
        data = progress_module.get_real_chart_data(session_id)
        return data
    except Exception as e:
        logger.error(f"Error fetching chart data: {e}")
        raise HTTPException(status_code=500, detail="Internal Server Error")
    
@router.get("/chart-view-am/{session_id}")
async def get_chart_page_am(session_id: str):
    # 경로 찾기 로직은 동일
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    root_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_file_dir))) # root까지 올라감 (back/app/routers -> root)
    # 안전하게 기존 방식대로 계산 (back/app/routers -> back/app -> back -> root)
    # 위 코드보다 기존에 쓰시던 방식을 그대로 쓰시는게 안전합니다.
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    app_dir = os.path.dirname(current_file_dir)
    back_dir = os.path.dirname(app_dir)
    root_dir = os.path.dirname(back_dir)

    file_path = os.path.join(root_dir, "front", "components", "dashboard_AM.html")
    
    if os.path.exists(file_path):
        return FileResponse(file_path)
    logger.error(f"AM Dashboard not found: {file_path}")
    return {"error": "File not found"}

@router.get("/chart-data-am/{session_id}")
async def get_chart_data_am(session_id: str):
    try:
        return progress_module.get_am_chart_data(session_id)
    except Exception as e:
        logger.error(f"AM API Error: {e}")
        raise HTTPException(status_code=500, detail="Server Error")


# --- PM 관련 라우터 ---
@router.get("/chart-view-pm/{session_id}")
async def get_chart_page_pm(session_id: str):
    # 경로 계산 (위와 동일)
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    app_dir = os.path.dirname(current_file_dir)
    back_dir = os.path.dirname(app_dir)
    root_dir = os.path.dirname(back_dir)

    file_path = os.path.join(root_dir, "front", "components", "dashboard_PM.html")
    
    if os.path.exists(file_path):
        return FileResponse(file_path)
    logger.error(f"PM Dashboard not found: {file_path}")
    return {"error": "File not found"}

@router.get("/chart-data-pm/{session_id}")
async def get_chart_data_pm(session_id: str):
    try:
        return progress_module.get_pm_chart_data(session_id)
    except Exception as e:
        logger.error(f"PM API Error: {e}")
        raise HTTPException(status_code=500, detail="Server Error")
    
    
@router.get("/download-excel/{time_type}/{session_id}")
async def download_excel(time_type: str, session_id: str):
    try:
        # ... (경로 계산 로직 동일) ...
        current_file_dir = os.path.dirname(os.path.abspath(__file__))
        root_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_file_dir)))

        # [수정] Result 폴더 매핑 추가
        if time_type.lower() == "today":
            folder_name = "Sales_today"
        elif time_type.upper() == "GOAL":
            folder_name = "Sales_GOAL"
        elif time_type.upper() == "RESULT":  # ★ 추가됨
            folder_name = "Sales_result"
        else:
            folder_name = f"Sales_{time_type.upper()}" 
            
        target_dir = os.path.join(root_dir, "front", "progress_xls", folder_name)
        
        # ... (이하 파일 찾기 및 리턴 로직은 동일) ...
        search_pattern = os.path.join(target_dir, f"*{session_id}.xlsx")
        files = glob.glob(search_pattern)
        if not files:
            return {"error": f"Excel file not found in {target_dir}"}
        
        latest_file = max(files, key=os.path.getmtime)
        return FileResponse(path=latest_file, filename=os.path.basename(latest_file))
    except Exception as e:
        return {"error": str(e)}

@router.get("/chart-view-result/{session_id}")
async def get_chart_page_result(session_id: str):
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    root_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_file_dir)))
    file_path = os.path.join(root_dir, "front", "components", "dashboard_result.html")
    
    if os.path.exists(file_path):
        return FileResponse(file_path)
    return {"error": "Dashboard Result file not found"}

# 3. Result 차트 데이터 API
@router.get("/chart-data-result/{session_id}")
async def get_chart_data_result(session_id: str):
    try:
        return progress_module.get_result_chart_data(session_id)
    except Exception as e:
        logger.error(f"Result API Error: {e}")
        raise HTTPException(status_code=500, detail="Server Error")
    
@router.post("/generate-afternoon-plan/{session_id}")
async def generate_afternoon_plan(session_id: str):
    """
    오후 계획 생성 및 DB 업데이트 트리거
    """
    result = progress_module.execute_afternoon_adjustment(session_id)
    
    if result["status"] == "error":
        raise HTTPException(status_code=500, detail=result["message"])
    
    return result

# 1. 오전 리포트 업데이트 API
@router.post("/update-report-am/{session_id}")
async def update_report_am(session_id: str):
    """
    AM 리포트 엑셀 업데이트 (DB 실적 반영)
    """
    result = progress_module.execute_report_update(session_id, "AM")
    
    if result["status"] == "error":
        raise HTTPException(status_code=500, detail=result["message"])
    
    return result

# 2. 오후 리포트 업데이트 API
@router.post("/update-report-pm/{session_id}")
async def update_report_pm(session_id: str):
    """
    PM 리포트 엑셀 업데이트 (DB 실적 반영)
    """
    result = progress_module.execute_report_update(session_id, "PM")
    
    if result["status"] == "error":
        raise HTTPException(status_code=500, detail=result["message"])
    
    return result


@router.post("/calc-rate-am/{session_id}")
async def calc_rate_am(session_id: str):
    """
    Sales_C_DB > today_sales_am_daily 테이블의 achievement_rate 계산 업데이트
    """
    result = progress_module.update_achievement_rate_db(session_id, "am")
    
    if result["status"] == "error":
        raise HTTPException(status_code=500, detail=result["message"])
    
    return result

# 4. PM 달성률 계산 및 업데이트 API
@router.post("/calc-rate-pm/{session_id}")
async def calc_rate_pm(session_id: str):
    """
    Sales_C_DB > today_sales_pm_daily 테이블의 achievement_rate 계산 업데이트
    """
    result = progress_module.update_achievement_rate_db(session_id, "pm")
    
    if result["status"] == "error":
        raise HTTPException(status_code=500, detail=result["message"])
    
    return result

@router.get("/ai-dashboard/{session_id}")
async def ai_dashboard_view(session_id: str):
    """
    AI 분석 대시보드 HTML 반환
    """
    # HTML 파일의 절대 경로 (서버 환경에 맞춰 수정 필요)
    # 기존 dashboard.html이 있는 위치와 같은 폴더로 지정
    file_path = "/home/air/goalskill_sales/front/components/dashboard_ai.html"
    
    if os.path.exists(file_path):
        return FileResponse(file_path)
    else:
        # 파일이 없으면 404 에러 리턴
        raise HTTPException(status_code=404, detail="dashboard_ai.html not found on server")


# ========================================
# デバッグ日誌 차트 (MBTI + SPI)
# ========================================
@router.get("/chart-view-debug/{session_id}")
async def get_chart_page_debug(session_id: str):
    """デバッグ日誌 대시보드 HTML 반환"""
    current_file_dir = os.path.dirname(os.path.abspath(__file__))
    app_dir = os.path.dirname(current_file_dir)
    back_dir = os.path.dirname(app_dir)
    root_dir = os.path.dirname(back_dir)

    file_path = os.path.join(root_dir, "front", "components", "dashboard_debug.html")

    if os.path.exists(file_path):
        return FileResponse(file_path)
    logger.error(f"Debug Dashboard not found: {file_path}")
    return {"error": "dashboard_debug.html not found"}


@router.get("/chart-data-debug/{session_id}")
async def get_chart_data_debug(session_id: str):
    """MBTI scores + SPI 데이터를 JSON으로 반환"""
    try:
        data = progress_module.get_debug_chart_data(session_id)
        return data
    except Exception as e:
        logger.error(f"Debug Chart Data API Error: {e}")
        raise HTTPException(status_code=500, detail="Internal Server Error")