from fastapi import APIRouter, UploadFile, File, Depends, HTTPException
from sqlalchemy.orm import Session
from database import SessionLocal
from models.models_profile_tables import (
    StudentProfile, EducationHistory, WorkExperience, Certification, Skill
)
from models.user_model import User
import os
import fitz  # PyMuPDF
import re
import phonenumbers
from utils.resume_groq_parser import parse_resume_with_groq

router = APIRouter()

RESUME_UPLOAD_DIR = "uploads/resumes"
os.makedirs(RESUME_UPLOAD_DIR, exist_ok=True)

VIDEO_UPLOAD_DIR = "uploads/videos"
os.makedirs(VIDEO_UPLOAD_DIR, exist_ok=True)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# ✅ Helper: Extract info from resume text (not used if using Groq)
def extract_resume_data(text: str, email: str) -> dict:
    lines = text.split("\n")
    clean_lines = [line.strip() for line in lines if line.strip()]

    phone = None
    for match in phonenumbers.PhoneNumberMatcher(text, "IN"):
        phone = phonenumbers.format_number(match.number, phonenumbers.PhoneNumberFormat.E164)
        break

    name = None
    for line in clean_lines:
        if email.lower() in line.lower() or (phone and phone in line):
            continue
        if len(line.split()) >= 2 and not re.search(r'\d', line):
            name = line
            break

    first_name = name.split()[0] if name else "Unknown"
    last_name = " ".join(name.split()[1:]) if name and len(name.split()) > 1 else "Unknown"

    skills = []
    skill_idx = next((i for i, l in enumerate(clean_lines) if "skill" in l.lower()), None)
    if skill_idx is not None:
        for i in range(skill_idx + 1, min(skill_idx + 6, len(clean_lines))):
            if clean_lines[i] == "" or len(clean_lines[i].split()) > 10:
                break
            skills += [s.strip() for s in re.split(r'[|,•]', clean_lines[i]) if s.strip()]

    education = []
    edu_keywords = ["B.Tech", "M.Tech", "Bachelor", "Master", "Graduation", "Intermediate", "Matriculation"]
    for line in clean_lines:
        if any(k.lower() in line.lower() for k in edu_keywords):
            education.append({
                "level": "Graduation" if "bachelor" in line.lower() or "b.tech" in line.lower() else "Other",
                "institution_name": line,
                "percentage_or_cgpa": "N/A",
                "address": "N/A",
                "is_pursuing": False
            })

    experience = []
    for i, line in enumerate(clean_lines):
        if re.search(r'\b(?:intern|developer|engineer|manager|designer)\b', line.lower()):
            experience.append({
                "job_title": line,
                "company_name": clean_lines[i + 1] if i + 1 < len(clean_lines) else "N/A",
                "duration_from": "N/A",
                "duration_to": "N/A",
                "description": clean_lines[i + 2] if i + 2 < len(clean_lines) else ""
            })

    return {
        "first_name": first_name,
        "last_name": last_name,
        "email": email,
        "contact": phone,
        "address": "N/A",
        "education": education,
        "experience": experience,
        "skills": skills
    }


# ✅ Upload resume and video
@router.post("/user/upload-resume/{email}")
async def upload_resume(
    email: str,
    file: UploadFile = File(...),
    video: UploadFile = File(...),
    db: Session = Depends(get_db)
):
    resume_filename = f"{email}_{file.filename}"
    resume_path = os.path.join(RESUME_UPLOAD_DIR, resume_filename)
    with open(resume_path, "wb") as buffer:
        buffer.write(await file.read())

    video_filename = f"{email}_{video.filename}"
    video_path = os.path.join(VIDEO_UPLOAD_DIR, video_filename)
    with open(video_path, "wb") as buffer:
        buffer.write(await video.read())

    try:
        doc = fitz.open(resume_path)
        text = ""
        for page in doc:
            text += page.get_text()
    except Exception:
        raise HTTPException(status_code=500, detail="Failed to extract text from PDF")

    try:
        parsed = parse_resume_with_groq(text, db)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Groq parsing failed: {str(e)}")

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

    existing = db.query(StudentProfile).filter(StudentProfile.user_id == user.id).first()
    if not existing:
        profile = StudentProfile(
            user_id=user.id,
            first_name=parsed.get("first_name"),
            last_name=parsed.get("last_name"),
            email=parsed.get("email"),
            contact=parsed.get("contact"),
            address=parsed.get("address"),
            education=parsed["education"][0]["level"] if parsed.get("education") else None,
            video_path=video_path
        )
        db.add(profile)
        db.commit()
        db.refresh(profile)
    else:
        profile = existing
        profile.video_path = video_path
        db.commit()

        # ✅ Delete previous entries to avoid duplication
        db.query(EducationHistory).filter(EducationHistory.student_id == profile.id).delete()
        db.query(WorkExperience).filter(WorkExperience.student_id == profile.id).delete()
        db.query(Skill).filter(Skill.student_id == profile.id).delete()
        db.commit()

    for edu in parsed.get("education", []):
        db.add(EducationHistory(
            student_id=profile.id,
            level=edu.get("level"),
            institution_name=edu.get("institution_name"),
            percentage_or_cgpa=edu.get("percentage_or_cgpa"),
            address=edu.get("address"),
            is_pursuing=edu.get("is_pursuing")
        ))

    for exp in parsed.get("experience", []):
        db.add(WorkExperience(
            student_id=profile.id,
            job_title=exp.get("job_title"),
            company_name=exp.get("company_name"),
            duration_from=exp.get("duration_from"),
            duration_to=exp.get("duration_to"),
            description=exp.get("description")
        ))

    for skill in parsed.get("skills", []):
        db.add(Skill(student_id=profile.id, name=skill))

    user.profile_completed = True
    db.commit()

    return {
        "message": "Resume and video uploaded successfully.",
        "video_path": video_path,
        "parsed_summary": {
            "name": f"{parsed.get('first_name', '')} {parsed.get('last_name', '')}",
            "email": parsed.get("email"),
            "phone": parsed.get("contact"),
            "skills": parsed.get("skills", []),
            "edu_count": len(parsed.get("education", [])),
            "exp_count": len(parsed.get("experience", []))
        }
    }


# ✅ Fetch full profile
@router.get("/user/resume-profile/{user_id}")
def get_full_resume_profile(user_id: int, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id, User.role == "user").first()
    if not user:
        raise HTTPException(404, detail="User not found")

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

    education = db.query(EducationHistory).filter(EducationHistory.student_id == profile.id).all()
    experience = db.query(WorkExperience).filter(WorkExperience.student_id == profile.id).all()
    certifications = db.query(Certification).filter(Certification.student_id == profile.id).all()
    skills = db.query(Skill).filter(Skill.student_id == profile.id).all()

    return {
        "user": {
            "id": user.id,
            "email": user.email
        },
        "profile": {
            "first_name": profile.first_name,
            "last_name": profile.last_name,
            "dob": profile.dob,
            "gender": profile.gender,
            "contact": profile.contact,
            "address": profile.address,
            "education_summary": profile.education,
            "profile_picture": getattr(profile, "profile_picture", None),
            "video_path": getattr(profile, "video_path", None)
        },
        "education": [
            {
                "level": e.level,
                "institution_name": e.institution_name,
                "percentage_or_cgpa": e.percentage_or_cgpa,
                "address": e.address,
                "is_pursuing": e.is_pursuing,
                "marksheet_path": e.marksheet_path
            } for e in education
        ],
        "experience": [
            {
                "job_title": e.job_title,
                "company_name": e.company_name,
                "duration_from": e.duration_from,
                "duration_to": e.duration_to,
                "description": e.description
            } for e in experience
        ],
        "certifications": [
            {
                "title": c.title,
                "organization": c.organization,
                "certificate_path": c.certificate_path
            } for c in certifications
        ],
        "skills": [s.name for s in skills]  # ✅ added skill list
    }
