import enum

from sqlalchemy import CheckConstraint, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.db.base import Base


class FormTypeEnum(str, enum.Enum):
    FORM_1 = "FORM_1"
    FORM_2 = "FORM_2"
    FORM_3 = "FORM_3"
    FORM_4 = "FORM_4"


class FormType(Base):
    __tablename__ = "form_type"
    __table_args__ = (
        CheckConstraint("scope IN ('GO','PD','RF')", name="ck_form_type_scope"),
        CheckConstraint(
            "storage_entity IN ('BUDGET_FORM','RF_PROJECT_REPORT')",
            name="ck_form_type_storage_entity",
        ),
        {"schema": "v3"},
    )

    code: Mapped[str] = mapped_column(String, primary_key=True)
    name: Mapped[str | None] = mapped_column(String)
    scope: Mapped[str | None] = mapped_column(String)
    storage_entity: Mapped[str | None] = mapped_column(String)

    
    SHEETS_BY_FORM_TYPE = {
        FormTypeEnum.FORM_1: ["AHR", "CAP", "OPER", "SMETA"],
        FormTypeEnum.FORM_2: ["AHR", "CAP", "OPER", "AHR_LIMIT", "AHR_RENT",
                "AHR_UTILITY", "AHR_SECURITY", "OTCH9F", "SMETA"],
        FormTypeEnum.FORM_3: ["LIMIT", "CURRENT_EXPENSES"],
        FormTypeEnum.FORM_4: ["AHR", "CAP", "OPER", "STRUCTURE", "SMETA"],
    }
    SECTIONS_BY_FORM_TYPE = {
        FormTypeEnum.FORM_1: ["plan", "contract_summary", "allocation", "sequestration", "reserve", "approved", "collegial", "ckk", "contract_detail", "q1", "q2", "q3", "q4", "totals"],
        FormTypeEnum.FORM_2: ["plan", "seq_dfip", "seq_ssp", "approved", "contract", "booking", "q1", "q2", "q3", "q4", "totals"],
        FormTypeEnum.FORM_3: ["q1", "q2", "q3", "q4", "year"],
        FormTypeEnum.FORM_4: ["plan", "seq_dfip", "approved", "contract", "booking", "q1", "q2", "q3", "q4", "totals", "contract_summary", "allocation", "reserve", "collegial", "ckk"],
    }

    _sheet_list_with_directions = {
        FormTypeEnum.FORM_1: [
            {
                "sheet_name": sheet_name,
                "direction": None,
            } for sheet_name in ["OPER", "SMETA"]
        ] + [
            {
                "sheet_name": sheet_name,
                "direction": direction
            } for sheet_name in ["AHR", "CAP"] for direction in ["Support", "Development"]
        ]
    }

    @property
    def sheet_list_with_directions(self) -> dict:
        return self._sheet_list_with_directions.get(
            self.code,
            [
                {
                    "sheet_name": sheet_name,
                    "direction": None,
                } for sheet_name in self.sheet_list
            ]
        )

    @property
    def sheet_list(self):
        return self.SHEETS_BY_FORM_TYPE.get(self.code, [])

    @property
    def section_list(self):
        return self.SECTIONS_BY_FORM_TYPE.get(self.code, [])
