from fastapi import APIRouter, Depends, HTTPException, Body, Request
from sqlalchemy.orm import Session
from auth.google_oauth import get_google_user
from auth.linkedin_oauth import get_linkedin_user
from database import SessionLocal
from models.models_profile_tables import RecruiterProfile
from models.user_model import User
from schemas.auth_schema import OTPRequest, OTPVerify, TokenResponse
from utils.jwt_utils import create_jwt_token
import random
from models.models_profile_tables import AdminProfile
from schemas.admin_schema import AdminProfileUpdate
from models.models_profile_tables import StudentProfile
from schemas.student_schema import StudentProfileUpdate
import os
from authlib.integrations.starlette_client import OAuth
from starlette.config import Config
from fastapi.responses import RedirectResponse


router = APIRouter()

otp_store = {}  # In-memory OTP store


# Starlette OAuth Config
config = Config(environ=os.environ)
oauth = OAuth(config)

# --- Google OAuth Config ---
oauth.register(
    name='google',
    client_id=os.getenv("GOOGLE_CLIENT_ID"),
    client_secret=os.getenv("GOOGLE_CLIENT_SECRET"),
    access_token_url='https://oauth2.googleapis.com/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    api_base_url='https://www.googleapis.com/oauth2/v2/',
    client_kwargs={'scope': 'openid email profile'},
)

# --- Facebook OAuth Config ---
oauth.register(
    name='facebook',
    client_id=os.getenv("FACEBOOK_CLIENT_ID"),
    client_secret=os.getenv("FACEBOOK_CLIENT_SECRET"),
    access_token_url='https://graph.facebook.com/v10.0/oauth/access_token',
    authorize_url='https://www.facebook.com/v10.0/dialog/oauth',
    api_base_url='https://graph.facebook.com/v10.0/',
    client_kwargs={'scope': 'email'},
)

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

@router.post("/signup")
def signup(
    name: str = Body(...),
    email: str = Body(...),
    role: str = Body(...),  # admin, recruiter, user
    db: Session = Depends(get_db)
):
    existing = db.query(User).filter(User.email == email).first()
    if existing:
        raise HTTPException(status_code=400, detail="User already exists")

    verified = True if role != "recruiter" else False
    new_user = User(name=name, email=email, role=role, verified=verified)
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return {"message": "User created successfully", "user_id": new_user.id}

@router.post("/login/request-otp")
def request_otp(data: OTPRequest, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == data.email).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    otp = str(random.randint(100000, 999999))
    otp_store[data.email] = otp
    print(f"[OTP for {data.email}]: {otp}")  # Replace with email sending in prod

    return {"message": "OTP sent to your email"}

@router.post("/login/verify-otp")
def verify_otp(data: OTPVerify, db: Session = Depends(get_db)):
    if otp_store.get(data.email) != data.otp:
        raise HTTPException(status_code=403, detail="Invalid OTP")

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

    login_info = f"[Login Attempt] Email: {user.email}, Role: {user.role}, Verified: {user.verified}"
    print(login_info)

    if not user.profile_completed:
        raise HTTPException(
            status_code=403,
            detail={
                "message": f"{user.role.capitalize()} profile is incomplete. Please complete profile first.",
                "profile_completed": False
            }
        )


    # ❌ Recruiter not verified
    if user.role == "recruiter" and not user.verified:
        raise HTTPException(
            status_code=403,
            detail={
                "message": "Recruiter not verified by admin yet.",
                "verified": user.verified
            }
        )

    # ❌ Recruiter/User profile not completed

    # ✅ Generate token and return
    token = create_jwt_token(user.email, user.role)
    del otp_store[data.email]

    return {
        "access_token": token,
        "token_type": "bearer",
        "id": user.id,
        "role": user.role,
        "verified": user.verified,
        "profile_completed": user.profile_completed,
        "log": login_info
    }


@router.get("/admin/unverified-recruiters")
def get_unverified_recruiters(db: Session = Depends(get_db)):
    from models.models_profile_tables import RecruiterProfile
    recruiters = db.query(User).filter(User.role == "recruiter", User.verified == False).all()
    result = []
    for r in recruiters:
        profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == r.id).first()
        result.append({
            "id": r.id,
            "name": r.name,
            "email": r.email,
            "verified": r.verified,
            "profile": {
                "first_name": getattr(profile, "first_name", None),
                "last_name": getattr(profile, "last_name", None),
                "introduction": getattr(profile, "introduction", None),
                "website": getattr(profile, "website", None),
                "year_founded": getattr(profile, "year_founded", None),
                "number_of_employees": getattr(profile, "number_of_employees", None),
                "location": getattr(profile, "location", None),
                "company_logo": getattr(profile, "company_logo", None)
            } if profile else None
        })
    return result


@router.patch("/admin/verify-recruiter/{recruiter_id}")
def verify_recruiter(recruiter_id: int, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == recruiter_id, User.role == "recruiter").first()
    if not user:
        raise HTTPException(status_code=404, detail="Recruiter not found")

    user.verified = True
    db.commit()
    return {"message": f"Recruiter {user.name} verified successfully."}

@router.get("/check-profile-status-by-email/{email}")
def check_profile_status_by_email(email: str, db: Session = Depends(get_db)):
    # First check if user exists
    user = db.query(User).filter(User.email == email).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    role = user.role
    profile = None
    required_fields = []

    if role == "recruiter":
        from models.models_profile_tables import RecruiterProfile
        profile = db.query(RecruiterProfile).filter(RecruiterProfile.user_id == user.id).first()
        required_fields = [
            profile and profile.first_name,
            profile and profile.last_name,
            profile and profile.introduction,
            profile and profile.email,
            profile and profile.location
        ]

    elif role == "user":
        from models.models_profile_tables import StudentProfile
        profile = db.query(StudentProfile).filter(StudentProfile.user_id == user.id).first()
        required_fields = [
            profile and profile.first_name,
            profile and profile.last_name,
            profile and profile.dob,
            profile and profile.gender,
            profile and profile.email
        ]

    elif role == "admin":
        from models.models_profile_tables import AdminProfile
        profile = db.query(AdminProfile).filter(AdminProfile.user_id == user.id).first()
        required_fields = [
            profile and profile.first_name,
            profile and profile.last_name,
            profile and profile.email
        ]
    else:
        raise HTTPException(status_code=400, detail="Invalid role")

    is_complete = profile is not None and all(required_fields)

    return {
        "email": email,
        "user_id": user.id,
        "role": role,
        "profile_complete": is_complete,
        "profile_data": {
            "first_name": getattr(profile, "first_name", None),
            "last_name": getattr(profile, "last_name", None),
            "email": getattr(profile, "email", None)
        } if profile else None
    }

@router.put("/update-profile/{user_id}")
def update_profile(
    user_id: int,
    payload: dict = Body(...),
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    role = user.role
    profile_model = None

    if role == "recruiter":
        from models.models_profile_tables import RecruiterProfile
        profile_model = RecruiterProfile
    elif role == "user":
        from models.models_profile_tables import StudentProfile
        profile_model = StudentProfile
    elif role == "admin":
        from models.models_profile_tables import AdminProfile
        profile_model = AdminProfile
    else:
        raise HTTPException(status_code=400, detail="Invalid role")

    profile = db.query(profile_model).filter(profile_model.user_id == user_id).first()

    if not profile:
        profile = profile_model(user_id=user_id, **payload)
        db.add(profile)
    else:
        for key, value in payload.items():
            setattr(profile, key, value)

    user.profile_completed = True
    db.commit()
    return {
        "message": f"{role.capitalize()} profile created/updated successfully.",
        "profile_type": role,
        "profile_fields": payload
    }

@router.get("/login/google")
async def google_login(code: str):
    return await get_google_user(code)


@router.get("/login/linkedin")
async def linkedin_login(code: str):
    return await get_linkedin_user(code)