import os
import shutil
import uuid
from fastapi import APIRouter, UploadFile, File, Form, HTTPException
from app.schemas.selfpr_schemas import SelfPRResponse, SelfPRLogResponse
from app.models import selfpr_module
from app.core.config import ZOOM_MEETING_ID, ZOOM_MEETING_PASSWORD

router = APIRouter(
    prefix="/goal-skill-t/api/selfpr",
    tags=["SelfPR"]
)


UPLOAD_DIR = "uploads"

# Import Calendar Utility
try:
    from app.utils.google_calendar import create_event
    # print("[DEBUG] google_calendar imported successfully")
except ImportError as e:
    # print(f"[DEBUG] Failed to import google_calendar: {e}")
    create_event = None


# Ensure upload directory exists
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

@router.post("/step1_save", response_model=SelfPRResponse)
async def step1_save(
    session_id: str = Form(...),
    selected_items: str = Form(...)
):
    try:
        # Step 1: 체크박스 선택 정보만 저장 (나머지는 None)
        selfpr_module.insert_selfpr_log(
            session_id=session_id, 
            selected_items=selected_items
        )
        
        return SelfPRResponse(
            status="success",
            message="Step 1 saved successfully."
        )

    except Exception as e:
        print(f"[SelfPR Step1 Error] {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/step2_save", response_model=SelfPRResponse)
async def step2_save(
    session_id: str = Form(...),
    company_name: str = Form(None), # Changed from user_name. Can be None if not provided.
    user_age: int = Form(...),
    # school_name: str = Form(...), # Removed
    selected_items: str = Form(...),
    meeting_time: str = Form(None), # Added
    origin: str = Form(None), # Added for full URL construction
    photo: UploadFile = File(None) # 이미 저장된 게 있을 수 있으므로 Optional
):
    try:
        # 0. Get Real User Name from DB
        real_user_name = selfpr_module.get_username_from_profile(session_id)
        
        # If company_name is provided, we can use it. 
        # For now, let's assume valid user_name for template is the one from DB.
        user_name = real_user_name
        
        # 1. 파일 처리
        relative_path = None
        
        # 새 파일이 업로드된 경우
        if photo:
            file_ext = photo.filename.split('.')[-1] if '.' in photo.filename else "jpg"
            unique_filename = f"{uuid.uuid4()}.{file_ext}"
            file_path = os.path.join(UPLOAD_DIR, unique_filename)
            
            with open(file_path, "wb") as buffer:
                shutil.copyfileobj(photo.file, buffer)
            
            relative_path = f"/{UPLOAD_DIR}/{unique_filename}"
        
        # 파일이 없고 기존 기록이 있다면? (DB 조회 필요)
        # 하지만 간단하게 하기 위해, 파일이 안 넘어왔으면 기존 DB 값을 유지하는 로직은 
        # service/dao 레벨에서 처리하거나, 프론트에서 기존 경로를 보내주는 게 좋음.
        # 여기서는 "파일이 있으면 덮어쓰기, 없으면 기존 값 유지"를 위해 DB 조회를 먼저 합니다.
        if not relative_path:
            old_log = selfpr_module.get_selfpr_log(session_id)
            if old_log and old_log['photo_path']:
                relative_path = old_log['photo_path']

        # 2. HTML 생성
        # Server absolute path preferred
        SERVER_FRONT_DIR = "/home/air/goalskill_t/front/self_pr"
        
        # Check if server path is valid (Linux/Production env)
        if os.path.exists("/home/air/goalskill_t"):
            front_selfpr_dir = SERVER_FRONT_DIR
        else:
            # Local fallback (Windows/Dev env)
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # back/app/routers -> back/app -> back -> ../front/self_pr
            front_selfpr_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(current_dir))), "front", "self_pr")
        
        if not os.path.exists(front_selfpr_dir):
            os.makedirs(front_selfpr_dir)
            
        html_filename = f"{session_id}.html"
        html_path = os.path.join(front_selfpr_dir, html_filename)
        
        # HTML 내 이미지 경로 조정 (front/self_pr 기준 back/uploads 접근)
        # relative_path: /uploads/xxxx.jpg
        # Target: ../../back/uploads/xxxx.jpg
        # HTML 내 이미지 경로 조정 (front/self_pr 기준 back/uploads 접근)
        # relative_path: /uploads/xxxx.jpg
        # Target: ../../back/uploads/xxxx.jpg
        html_image_path = f"../../back{relative_path}" if relative_path else ""
        
        # HTML 템플릿 preparing tags
        import json
        try:
            items_list = json.loads(selected_items)
        except:
             # Fallback if evaluation or load checks fail, though json.loads is standard from frontend stringify
            try:
                items_list = eval(selected_items)
            except:
                items_list = []
        
        
        display_tags = []
        for item in items_list:
            if item == "資格":
                display_tags.append("基本情報技術者")
            else:

                display_tags.append(item)
                
        # Paiza display logic
        paiza_display = "d-none"
        if "PYTHON B" in items_list:
            paiza_display = ""






        # HTML 템플릿 (Using ryu_template.html)
        # Load Template
        # back/app/routers -> back/app -> templates -> ryu_template.html
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        template_path = os.path.join(base_dir, "templates", "ryu_template.html")
        
        if not os.path.exists(template_path):
             # Fallback if template missing (should not happen if deployed correctly)
             print(f"[ERROR] Template not found at {template_path}")
             raise HTTPException(status_code=500, detail="Template file not found.")

        with open(template_path, "r", encoding="utf-8") as f:
            template_content = f.read()

        # Replace Placeholders
        # Note: html_image_path logic remains same (../../back/uploads/...)
        # But if the template uses /static/images/default.png, we replace it.
        # If user didn't upload photo, html_image_path is "" -> broken image?
        # If html_image_path is empty, we should maybe keep the default or use a placeholder.
        # original check: if relative_path else ""
        
        # If no photo uploaded, use a default from the template? 
        # The template has {{profile_image}}. 
        # ryu_sio.com default is /static/images/류시온.png
        # If html_image_path is empty, let's use the default or a generic default.
        final_image_path = html_image_path if html_image_path else "../static/images/류시온.png"

        school_val_for_template = company_name if company_name else ""

        html_content = template_content.replace("{{user_name}}", user_name) \
                                       .replace("{{user_age}}", str(user_age)) \
                                       .replace("{{school_name}}", school_val_for_template) \
                                       .replace("{{profile_image}}", final_image_path) \
                                       .replace("{{custom_css_link}}", "") \
                                       .replace("{{custom_js_script}}", "") \
                                       .replace("{{paiza_display}}", paiza_display)


        
        # Tech Stack Injection (Optional: Create badges)
        # We can also replace {{tech_stack_html}} if we added it, but I didn't add it in the previous step.
        # I only added user_name, age, school, profile_image.
        # If I want to support tech stack, I need to update the template first.
        # For now, I will stick to what I added to the template.
        
        with open(html_path, "w", encoding="utf-8") as f:
            f.write(html_content)

        # 3. URL 생성 및 DB 저장
        # User requested specific path: .../goalskill_t/front/self_pr/...
        # API base assumed: .../goal-skill-t/api
        # Moving up to root and into goalskill_t
        site_url = f"/../../goalskill_t/front/self_pr/{html_filename}" 
        
        selfpr_module.insert_selfpr_log(
            session_id=session_id, 
            user_name=user_name, 
            user_age=user_age, 
            company_name=company_name, 
            photo_path=relative_path, 
            selected_items=selected_items,
            site_url=site_url
        )
        
        # Check for Zoom Config and "面接" item if needed?
        # Ideally we should pass the link anyway if config exists, specific logic can be in Front
        # But to be secure, maybe only send if requested. 
        # For simple flow, just send it if configured.
        
        zoom_link = None
        zoom_password_val = None
        print(f"[DEBUG] Checking Zoom Config - ID: {ZOOM_MEETING_ID}, PW present: {bool(ZOOM_MEETING_PASSWORD)}")
        
        if ZOOM_MEETING_ID and ZOOM_MEETING_PASSWORD:
            zoom_link = f"https://zoom.us/j/{ZOOM_MEETING_ID}?pwd={ZOOM_MEETING_PASSWORD}"
            zoom_password_val = ZOOM_MEETING_PASSWORD
            # print(f"[DEBUG] Zoom Link Generated: {zoom_link}")
            

            # Google Calendar Logic (New - Auto Schedule 7 days later)
            calendar_url = None
            meeting_time_str = None
            
            # print(f"[DEBUG] create_event present: {bool(create_event)}")
            # print(f"[DEBUG] items_list: {items_list}")
            

            if create_event and "面接" in items_list:
                import datetime
                # Calculate 7 days later
                target_date = datetime.datetime.now() + datetime.timedelta(days=7)
                
                # Set fixed time to 14:00
                target_date = target_date.replace(hour=14, minute=0, second=0, microsecond=0)
                meeting_time_str = target_date.isoformat()
                
                # Fix Zoom Link (remove spaces)
                clean_zoom_link = zoom_link.replace(" ", "")
                
                # Construct full URL for calendar description
                full_site_url = site_url
                if origin:
                    clean_path = site_url.replace("/../..", "")
                    full_site_url = f"{origin}{clean_path}"

                # print(f"[DEBUG] Creating Auto Calendar Event for: {meeting_time_str}")
                calendar_url = create_event(
                    summary=f"面接: {user_name}",
                    description=f"候補者名: {user_name}\n会社名: {company_name}\n自己紹介サイト: {full_site_url}\nZoomミーティング: {clean_zoom_link}\nパスコード: {zoom_password_val}",
                    start_time_str=meeting_time_str,
                    location="札幌市"
                )
        else:
            # print("[DEBUG] Zoom Config missing, link not generated.")
            meeting_time_str = None
            calendar_url = None

        return SelfPRResponse(
            status="success",
            message="Self-PR generated successfully.",
            file_path=relative_path,
            site_url=site_url,
            zoom_link=zoom_link,
            zoom_password=zoom_password_val,
            meeting_time=meeting_time_str,
            calendar_url=calendar_url
        )

    except Exception as e:
        print(f"[SelfPR Step2 Error] {e}")
        import traceback
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/log/{session_id}", response_model=SelfPRLogResponse)
async def get_selfpr_log(session_id: str):
    log = selfpr_module.get_selfpr_log(session_id)
    if not log:
        return SelfPRLogResponse(found=False)
    
    return SelfPRLogResponse(
        found=True,
        data=log 
    )
