import os
import uuid
import shutil
from fastapi import UploadFile, HTTPException
from sqlalchemy.orm import Session
from models.models import KYCVerification, User,Notification

UPLOAD_DIR = "uploads/kyc"
os.makedirs(UPLOAD_DIR, exist_ok=True)
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "pdf"}

def allowed_file(filename: str):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS

async def upload_kyc_documents(
    user: User,
    front_image: UploadFile,
    back_image: UploadFile,
    db: Session,
):
    # Validation des fichiers
    if not allowed_file(front_image.filename) or not allowed_file(back_image.filename):
        raise HTTPException(status_code=400, detail="Invalid file type")

    # Chemins uniques
    front_image_path = os.path.join(UPLOAD_DIR, f"{user.id}_front_{uuid.uuid4()}_{front_image.filename}")
    back_image_path = os.path.join(UPLOAD_DIR, f"{user.id}_back_{uuid.uuid4()}_{back_image.filename}")

    # Sauvegarde des fichiers
    with open(front_image_path, "wb") as buffer:
        shutil.copyfileobj(front_image.file, buffer)

    with open(back_image_path, "wb") as buffer:
        shutil.copyfileobj(back_image.file, buffer)
    
    db_kyc = db.query(KYCVerification).filter(KYCVerification.user_id == user.id).first()
    if db_kyc and db_kyc.status == "pending":
        raise HTTPException(status_code=400, detail="KYC already pending review")
    if db_kyc:
        raise HTTPException(status_code=400, detail="KYC already submitted")

    # Création de l'enregistrement KYC
    kyc_verification = KYCVerification(
        id=str(uuid.uuid4()),
        user_id=user.id,
        document_front_image=front_image_path,
        document_back_image=back_image_path,
        status="pending"
    )

    try:
        db.add(kyc_verification)
        db.commit()
        db.refresh(kyc_verification)
        notification = Notification(
            id=str(uuid.uuid4()),
            user_id=user.id,
            message=f"Votre pieces a été soumis avec success et est en cours de vérification.",
            title="Verification KYC Soumise",
            type="kyc",
        )
        db.add(notification)
        db.commit()
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"KYC upload failed: {e}")


    return {
        "message": "KYC documents uploaded successfully",
        "kyc_verification_id": kyc_verification.id,
    }


async def get_kyc_status(user: User, db: Session):
    kyc_record = db.query(KYCVerification).filter(KYCVerification.user_id == user.id).first()
    if not kyc_record:
        return {"status": "not_submitted"}

    return {
        "status": kyc_record.status,
        "submitted_at": kyc_record.created_at,
        "reviewed_at": kyc_record.reviewed_at,
    }
async def validate_kyc(kyc_id: str, db: Session):

    kyc_record = db.query(KYCVerification).filter(KYCVerification.id == kyc_id).first()

    if not kyc_record:
        raise HTTPException(status_code=404, detail="KYC non trouvé")

    if kyc_record.status != "pending":
        raise HTTPException(status_code=400, detail="Ce KYC n'est pas en attente")

    kyc_record.status = "approved"
    kyc_record.kyc_active = True

    user = kyc_record.user

    try:
        db.commit()
        db.refresh(kyc_record)

        notification = Notification(
            id=str(uuid.uuid4()),
            user_id=user.id,
            message="Votre pièce a été validée.",
            title="KYC approuvé",
            type="kyc",
        )

        db.add(notification)
        db.commit()

        return {"message": "KYC validé avec succès"}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"KYC validation failed: {str(e)}")

async def refuse_kyc(kyc_record: KYCVerification, db: Session):

    # Vérifier que le KYC est en attente
    if kyc_record.status != "pending":
        raise HTTPException(status_code=400, detail="Ce KYC n'est pas en attente")

    user = kyc_record.user

    kyc_record.status = "rejected"

    try:
        db.commit()
        db.refresh(kyc_record)

        notification = Notification(
            id=str(uuid.uuid4()),
            user_id=user.id,
            message="Votre pièce n'a pas été approuvée. Veuillez réessayer.",
            title="KYC rejeté",
            type="kyc",
        )

        db.add(notification)
        db.commit()

        return {"message": "KYC refusé avec succès"}

    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=f"KYC refusal failed: {str(e)}")
