import os
import shutil
from fastapi.responses import FileResponse
import pandas as pd
from fastapi import UploadFile, HTTPException
from sqlalchemy.orm import Session
from app.dependency.authantication import JWTPayloadSchema
from app.models.main.group import TblGroup
from app.models.main.student import TblStudent


UPLOAD_DIR = "uploads"
ALLOWED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".svg"}
MAX_FILE_SIZE_MB = 50
os.makedirs(UPLOAD_DIR, exist_ok=True)

class CorporateStoreService:
    
    def __init__(self, db:Session, token:JWTPayloadSchema):
        self.db = db
        self.token = token
        
    def validate_file(file: UploadFile):
        ext = os.path.splitext(file.filename)[1].lower()
        if ext not in ALLOWED_EXTENSIONS:
            raise HTTPException(status_code=400,detail=f"❌ Unsupported file format: {ext}. "f"Allowed formats: PNG, JPG, JPEG, SVG.")
        
    async def upload_corporate_and_concept_level_organizational(self, file: UploadFile):
    # Validate file
        CorporateStoreService.validate_file(file)
        contents = await file.read()
        size_mb = len(contents) / (1024 * 1024)
        if size_mb > MAX_FILE_SIZE_MB:
            raise HTTPException(
                status_code=400,
                detail=f"❌ File size {size_mb:.2f} MB exceeds maximum {MAX_FILE_SIZE_MB} MB."
            )
        await file.seek(0)

        # Get student from token
        student_id = getattr(self.token, "student_id", None)
        if student_id is None:
            raise HTTPException(status_code=400, detail="student_id missing in token")

        student = self.db.query(TblStudent).filter(TblStudent.student_id == student_id).first()
        if not student:
            raise HTTPException(status_code=404, detail="Student not found")

        if not student.group:
            raise HTTPException(status_code=404, detail="Group not assigned")

        group = student.group

        # Delete old file if exists
        old_file_path = group.corporate_and_concept_level_organisational_chart
        if old_file_path and os.path.exists(old_file_path):
            os.remove(old_file_path)

        # Save new file
        save_path = os.path.join(UPLOAD_DIR, file.filename)
        with open(save_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Update DB
        group.corporate_and_concept_level_organisational_chart = save_path
        self.db.commit()
        self.db.refresh(group)

        return {
            "message": "✅ File uploaded and old file replaced successfully!",
            "group_id": group.group_id,
            "filename": save_path,
            "db_path": group.corporate_and_concept_level_organisational_chart
        }
        
        
    async def get_image_corporate(self):
        get_image = self.db.query(TblGroup.corporate_and_concept_level_organisational_chart).first()
        if not get_image:
            return {"error": "No image found"}
        # file_path = get_image
        # file_path = get_image[0] if isinstance(get_image, tuple) else get_image
        paths = [r[0] if isinstance(r, tuple) else r for r in get_image]
        file_path = paths[0]
        if not os.path.exists(file_path):
            return {"error": "File does not exist on server"}
        return FileResponse(file_path, media_type="image/jpeg")
        


    async def upload_store_level_organization_chart(self, file: UploadFile):
        # Validate file
        CorporateStoreService.validate_file(file)
        contents = await file.read()
        size_mb = len(contents) / (1024 * 1024)
        if size_mb > MAX_FILE_SIZE_MB:
            raise HTTPException(
                status_code=400,
                detail=f"❌ File size {size_mb:.2f} MB exceeds maximum {MAX_FILE_SIZE_MB} MB."
            )
        await file.seek(0)

        # Get student from token
        student_id = getattr(self.token, "student_id", None)
        if student_id is None:
            raise HTTPException(status_code=400, detail="student_id missing in token")

        student = self.db.query(TblStudent).filter(TblStudent.student_id == student_id).first()
        if not student:
            raise HTTPException(status_code=404, detail="Student not found")

        if not student.group:
            raise HTTPException(status_code=404, detail="Group not assigned")

        group = student.group

        # Delete old file if exists
        old_file_path = group.store_level_organisational_chart
        if old_file_path and os.path.exists(old_file_path):
            os.remove(old_file_path)

        # Save new file
        save_path = os.path.join(UPLOAD_DIR, file.filename)
        with open(save_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # Update DB
        group.store_level_organisational_chart = save_path
        self.db.commit()
        self.db.refresh(group)

        return {
            "message": "✅ File uploaded and old file replaced successfully!",
            "group_id": group.group_id,
            "filename": save_path,
            "db_path": group.store_level_organisational_chart
        }

        
    async def get_image_store_level(self):
        get_image = self.db.query(TblGroup.store_level_organisational_chart).first()
        if not get_image:
            return {"error" : "No image found"}
        paths = [r[0] if isinstance(r, tuple) else r for r in get_image]
        file_path = paths[0]
        if not os.path.exists(file_path):
            return {"error": "File does not exist on server"}
        return FileResponse(file_path, media_type="image/jpeg")
        