from fastapi import APIRouter, Depends, HTTPException, Body
from sqlalchemy.orm import Session
from database import SessionLocal
from models.models_profile_tables import RecruiterProfile
from models.user_model import User
from fastapi import File, UploadFile
import os
import shutil
from fastapi import File, UploadFile
import os
import shutil

# Create uploads directory if it doesn't exist
UPLOAD_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "uploads")
os.makedirs(UPLOAD_DIR, exist_ok=True)

router = APIRouter()

# ✅ Field-to-questions map
QUESTION_MAP = {
    "first_name": [
        "What's your first name?",
        "Please enter your given name.",
        "May I know your first name?",
        "Could you tell me your given name?",
        "Kindly share your first name.",
        "How should we address you by your first name?",
        "What do people usually call you?",
        "Can you type in your first name, please?",
        "Enter your name as it appears on official documents.",
        "Let's start with your first name."
    ],
    "last_name": [
        "What's your last name?",
        "Can you share your family name?",
        "Please provide your surname.",
        "What’s your legal last name?",
        "Kindly enter your last name.",
        "Tell me your family or ancestral name.",
        "How does your last name appear on official records?",
        "Could you type your last name here?",
        "What’s the second part of your full name?",
        "Let’s complete your full name with your last name."
    ],
    "email": [
        "What’s your business email?",
        "Please provide your professional email address.",
        "Can I have your email ID?",
        "Enter your email for contact purposes.",
        "What’s your official email address?",
        "Kindly share your email address.",
        "How can we reach you via email?",
        "Please type your primary work email.",
        "What email address should we use?",
        "Let’s start with your email for communication."
    ],
    "introduction": [
        "Tell us briefly about you and your company.",
        "Could you introduce your organization?",
        "What does your company do?",
        "Can you give a short intro about yourself?",
        "Share a short summary about your background.",
        "Introduce your role and your business.",
        "Give us a snapshot of your professional journey.",
        "What’s your company’s mission or vision?",
        "Who are you and what do you do?",
        "Describe your company in a few lines."
    ],
    "website": [
        "Do you have a website or portfolio link?",
        "What’s your company’s website?",
        "Can you share your website URL?",
        "Please provide your business website.",
        "Where can we learn more about your company?",
        "Drop your official website link here.",
        "Do you have an online presence?",
        "Type your company’s domain or portfolio page.",
        "Where can we find your work online?",
        "Let’s get your website address."
    ],
    "year_founded": [
        "When was your company founded?",
        "Which year did you start your business?",
        "In what year did the company begin?",
        "Tell us the year your venture was established.",
        "How long has your company been running?",
        "What’s the foundation year of your company?",
        "When did your operations start?",
        "Since what year have you been in business?",
        "What year marks your launch?",
        "Enter the year your company was founded."
    ],
    "number_of_employees": [
        "How many employees are in your company?",
        "What’s the size of your team?",
        "How big is your workforce?",
        "Can you share your team’s strength?",
        "What’s the total number of employees?",
        "Roughly how many people work for your company?",
        "How many staff members do you have?",
        "What’s the headcount at your company?",
        "Enter the number of your active team members.",
        "Share your team size estimate."
    ],
    "location": [
        "Where is your company located?",
        "Which city is your office based in?",
        "What’s your business location?",
        "Where are you currently operating from?",
        "Can you tell us your city and state?",
        "Share your office’s primary location.",
        "Where is your headquarters situated?",
        "Enter your current business address.",
        "In which region is your company based?",
        "Mention the city where your company resides."
    ]
}


# ✅ DB session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# ✅ GET all chat questions
@router.get("/recruiter/chat-questions")
def get_chat_questions():
    return [
        {"field": field, "questions": questions}
        for field, questions in QUESTION_MAP.items()
    ]

@router.post("/recruiter/chat-update-profile/{email}")
def chat_update_profile_by_email(
    email: str,
    field: str = Body(...),
    answer: str = Body(...),
    db: Session = Depends(get_db)
):
    if field not in QUESTION_MAP:
        raise HTTPException(status_code=400, detail="Invalid field name")

    user = db.query(User).filter(User.email == email, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()

    if not profile:
        if field in ["first_name", "last_name", "email"]:
            profile_data = {"user_id": user.id, field: answer}
            profile = RecruiterProfile(**profile_data)
            db.add(profile)
        else:
            raise HTTPException(
                status_code=400,
                detail="Profile must start with first_name, last_name, or email."
            )
    else:
        setattr(profile, field, answer)

    required_fields = [
        profile.first_name,
        profile.last_name,
        profile.email,
        profile.introduction,
        profile.website,
        profile.year_founded,
        profile.number_of_employees,
        profile.location
    ]

    if all(required_fields):
        user.profile_completed = True

    db.commit()

    return {
        "message": f"Answer for '{field}' saved.",
        "profile_completed": user.profile_completed
    }


# ✅ POST single answer to a field
# @router.post("/recruiter/chat-update-profile/{user_id}")
# def chat_update_profile(
#     user_id: int,
#     field: str = Body(...),
#     answer: str = Body(...),
#     db: Session = Depends(get_db)
# ):
#     # Check if valid field
#     if field not in QUESTION_MAP:
#         raise HTTPException(status_code=400, detail="Invalid field name")

#     # Validate user
#     user = db.query(User).filter(User.id == user_id, User.role == "recruiter").first()
#     if not user:
#         raise HTTPException(status_code=404, detail="Recruiter not found")

#     # Fetch profile
#     profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user_id).first()

#     # First-time insert
#     if not profile:
#         profile_data = {
#             "user_id": user_id,
#             "first_name": None,
#             "last_name": None,
#             "email": None,
#             field: answer
#         }
#         profile = RecruiterProfile(**profile_data)
#         db.add(profile)
#     else:
#         setattr(profile, field, answer)

#     try:
#         db.commit()
#         return {
#             "message": f"Answer for '{field}' saved.",
#             "profile_completed": False
#         }
#     except Exception as e:
#         db.rollback()
#         raise HTTPException(
#             status_code=400,
#             detail=f"Error saving profile: {str(e)}"
#         )

@router.get("/recruiter/profile/{email}")
def get_recruiter_profile(email: str, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == email, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()
    if not profile:
        raise HTTPException(status_code=404, detail="Recruiter profile not found")

    return {
        "user_id": profile.user_id,
        "first_name": profile.first_name,
        "last_name": profile.last_name,
        "email": profile.email,
        "introduction": profile.introduction,
        "website": profile.website,
        "year_founded": profile.year_founded,
        "number_of_employees": profile.number_of_employees,
        "location": profile.location
    }




@router.post("/recruiter/upload-logo/{email}")
async def upload_logo(
    email: str,
    logo: UploadFile = File(...),
    db: Session = Depends(get_db)
):
    # Validate user
    user = db.query(User).filter(User.email == email, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    # Get profile
    profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()
    if not profile:
        raise HTTPException(status_code=404, detail="Profile not found")

    # Validate file type
    if not logo.content_type.startswith('image/'):
        raise HTTPException(status_code=400, detail="File must be an image")

    # Create unique filename
    file_extension = os.path.splitext(logo.filename)[1]
    filename = f"logo_{user.id}{file_extension}"
    file_path = os.path.join(UPLOAD_DIR, filename)

    # Delete old logo if exists
    if profile.company_logo and os.path.exists(profile.company_logo):
        os.remove(profile.company_logo)

    # Save new logo
    try:
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(logo.file, buffer)

        profile.company_logo = f"uploads/{filename}"  # ✅ Save relative path
        db.commit()

        return {
    "message": "Logo uploaded successfully",
    "file_url": f"http://127.0.0.1:8000/uploads/{filename}"
}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/recruiter/logo/{email}")
def get_recruiter_logo(email: str, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == email, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()
    if not profile or not profile.company_logo:
        raise HTTPException(status_code=404, detail="Logo not found")

    return {
        "logo_url": f"http://127.0.0.1:8000/{profile.company_logo}"
    }

@router.delete("/recruiter/delete-logo/{email}")
async def delete_logo(
    email: str,
    db: Session = Depends(get_db)
):
    # Validate user
    user = db.query(User).filter(User.email == email, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    # Get profile
    profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()
    if not profile or not profile.company_logo:
        raise HTTPException(status_code=404, detail="No logo found")

    # Delete logo file
    try:
        if os.path.exists(profile.company_logo):
            os.remove(profile.company_logo)

        profile.company_logo = None
        db.commit()

        return {"message": "Logo deleted successfully"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

from pydantic import BaseModel

class RecruiterProfileUpdate(BaseModel):
    first_name: str
    last_name: str
    email: str
    introduction: str
    website: str
    year_founded: str
    number_of_employees: str
    location: str

@router.put("/recruiter/update-profile/{email}")
def update_recruiter_profile(
    email: str,
    data: RecruiterProfileUpdate,
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.email == email, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()
    if not profile:
        profile = RecruiterProfile(user_id=user.id)
        db.add(profile)

    # Update all fields
    for field, value in data.dict().items():
        setattr(profile, field, value)

    # Mark profile as completed if all required fields are present
    required_fields = [
        profile.first_name,
        profile.last_name,
        profile.email,
        profile.introduction,
        profile.website,
        profile.year_founded,
        profile.number_of_employees,
        profile.location
    ]
    user.profile_completed = all(required_fields)

    db.commit()
    db.refresh(profile)

    return {
        "message": "Recruiter profile updated successfully",
        "profile_completed": user.profile_completed
    }