"""
Admin-managed dropdown masters: one table per list (production lines, AC makes, ...).

Every list table has the same core columns (id, code, label, sort_order, is_active,
timestamps); a few add typed columns of their own (see EXTRA_COLUMNS). The
master_list_registry table names each list, its table and its description, so the
admin screen and the API discover lists from the database.
"""
import uuid
from datetime import datetime, timezone
from sqlalchemy import Column, String, Boolean, DateTime, Integer, Text
from sqlalchemy.dialects.postgresql import UUID
from app.core.database import Base


def now_utc():
    return datetime.now(timezone.utc)


class MasterListRegistry(Base):
    __tablename__ = 'master_list_registry'

    list_code = Column(String(60), primary_key=True)           # e.g. AC_MAKE (used by the API/UI)
    table_name = Column(String(80), unique=True, nullable=False)  # e.g. ac_make_master
    label = Column(String(150), nullable=False)
    description = Column(Text)
    sort_order = Column(Integer, nullable=False, default=0)


class _MasterListColumns:
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    code = Column(String(120), unique=True, nullable=False)
    label = Column(String(300), nullable=False)
    sort_order = Column(Integer, nullable=False, default=0)
    is_active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime(timezone=True), default=now_utc)
    updated_at = Column(DateTime(timezone=True), default=now_utc, onupdate=now_utc)


# list_code -> table name. Order here does not matter; display order lives in the registry.
MASTER_LIST_TABLES = {
    'PRODUCTION_LINE': 'production_line_master',
    'AC_MAKE': 'ac_make_master',
    'INTERIOR_WORK': 'interior_work_master',
    'YARD_LOCATION': 'yard_location_master',
    'MACHINE_TYPE': 'machine_type_master',
    'INCOMING_MATERIAL_CATEGORY': 'incoming_material_category_master',
    'RENTAL_VENDOR': 'rental_vendor_master',
    'RENTAL_EQUIPMENT_TYPE': 'rental_equipment_type_master',
    'QA_VERIFICATION_METHOD': 'qa_verification_method_master',
    'PRODUCTION_HOLD_TYPE': 'production_hold_type_master',
    'PAYMENT_TERMS': 'payment_terms_master',
    'REGION': 'region_master',
    'ENQUIRY_TYPE': 'enquiry_type_master',
    'ENQUIRY_SOURCE': 'enquiry_source_master',
    'CHASSIS_DOCUMENT_TYPE': 'chassis_document_type_master',
    'GATE_PASS_ITEM': 'gate_pass_item_master',
    'THERMAL_CHECK_ITEM': 'thermal_check_item_master',
}

# Typed columns specific to one list. The API exposes them as `meta` keys.
EXTRA_COLUMNS = {
    'GATE_PASS_ITEM': {
        'default_qty': lambda: Column(Integer, nullable=False, default=1),
        'print_row': lambda: Column(Integer, nullable=False, default=1),
    },
}
# meta key used by the screens -> column name
META_KEYS = {'GATE_PASS_ITEM': {'default_qty': 'default_qty', 'row': 'print_row'}}


def _class_name(table_name: str) -> str:
    return ''.join(p.capitalize() for p in table_name.split('_'))


MASTER_LIST_MODELS = {}
for _code, _table in MASTER_LIST_TABLES.items():
    attrs = {'__tablename__': _table}
    for col_name, make in EXTRA_COLUMNS.get(_code, {}).items():
        attrs[col_name] = make()
    MASTER_LIST_MODELS[_code] = type(_class_name(_table), (_MasterListColumns, Base), attrs)
