import os
from typing import List

from openpyxl import load_workbook
from app.api.trading_month import schemas
from app.api.trading_month.schemas import TradingMonthCreate, TradingMonthResponce
from app.locale.messages import Messages
from sqlalchemy.orm import Session
from app.models.main.group import TblGroup
from app.models.main.trading_months import TblTradingMonth, TradingMonthBase
from app.utils.schemas_utils import CustomResponse

class TradingMonthService:
    def __init__(self, db: Session, token):
        self.db = db
        self.token = token
        
    async def create_trading_month(self, request: TradingMonthCreate):
        # 1️⃣ Validate group_id
        group = self.db.query(TblGroup).filter(TblGroup.group_id == request.group_id).first()
        if not group:
            raise CustomResponse(status="-1", message=f"group_id={request.group_id} does not exist")

        # 2️⃣ Save to DB
        trading_data = TradingMonthBase.model_validate(request.model_dump())
        TblTradingMonth.create(trading_data, self.db)
        self.db.commit()

        # 3️⃣ File paths
        EXCEL_PATH = "files/Simulation_Test_file_clean_final.xlsx"
        OUTPUT_PATH = "uploaded_files/Simulation_Test_file_clean_final_output.xlsx"
        os.makedirs("uploaded_files", exist_ok=True)

        # 4️⃣ Load workbook
        workbook = load_workbook(OUTPUT_PATH if os.path.exists(OUTPUT_PATH) else EXCEL_PATH)

        # 5️⃣ Define target cell locations (adjust cell positions if needed)
        param_to_cell = {
            "store_a_trading_months": "K28",  # for Assu Sum Mod A
            "store_b_trading_months": "K28",  # for Assu Sum Mod B
        }

        # 6️⃣ Update sheet “Assu Sum Mod A”
        sheet_a = workbook["Assu Sum Mod A"]
        cell_a = param_to_cell["store_a_trading_months"]
        sheet_a[cell_a] = trading_data.store_a_trading_months

        # 7️⃣ Update sheet “Assu Sum Mod B”
        sheet_b = workbook["Assu Sum Mod B"]
        cell_b = param_to_cell["store_b_trading_months"]
        sheet_b[cell_b] = trading_data.store_b_trading_months

        # 8️⃣ Save workbook
        workbook.save(OUTPUT_PATH)
        workbook.close()

        return CustomResponse(status="1", message="Trading Month created and Excel updated successfully")

    async def get_trading(self, group_id: int):
        segment = TblTradingMonth.get_by_group_id(group_id, self.db)
        if not segment:
            return CustomResponse(status="-1", message=Messages.TRADING_NOT)
        return [TradingMonthResponce.model_validate(get_group) for get_group in segment]
    
    async def update_trading(self, request: List[schemas.TradingMonthUpdate]):
        last_updated_obj = None

        for req in request:
            updated = TradingMonthBase.model_validate(req.model_dump())

            if updated.trading_id is None:
                return CustomResponse(status="-1", message=Messages.TRADING_NOT)

            TblTradingMonth.update(updated.trading_id, updated, self.db)

            # Fetch ORM model for refresh
            last_updated_obj = (
                self.db.query(TblTradingMonth)
                .filter(TblTradingMonth.trading_id == updated.trading_id)
                .first()
            )

        self.db.commit()

        if last_updated_obj:
            self.db.refresh(last_updated_obj)

        # Excel update using updated object (Pydantic or ORM)
        # Prefer ORM values:
        store_a = last_updated_obj.store_a_trading_months
        store_b = last_updated_obj.store_b_trading_months

        # Paths
        EXCEL_PATH = "files/Simulation_Test_file_clean_final.xlsx"
        OUTPUT_PATH = "uploaded_files/Simulation_Test_file_clean_final_output.xlsx"
        os.makedirs("uploaded_files", exist_ok=True)

        # Load workbook
        workbook = load_workbook(OUTPUT_PATH if os.path.exists(OUTPUT_PATH) else EXCEL_PATH)

        # Update Sheet A
        sheet_a = workbook["Assu Sum Mod A"]
        sheet_a["K28"] = store_a

        # Update Sheet B
        sheet_b = workbook["Assu Sum Mod B"]
        sheet_b["K28"] = store_b

        workbook.save(OUTPUT_PATH)
        workbook.close()

        return CustomResponse(status="1", message=Messages.TRADING_UPDATE)
    
    async def delete_trading(self, trading_id:int):
        deleted = TblTradingMonth.delete(trading_id, self.db)
        if not deleted:
            return CustomResponse(status="-1", message=Messages.TRADING_NOT)
        return CustomResponse(status="1", message=Messages.TRADING_DELETE)
    
    