"""PXE/GE-Enforce pc-type -> ComputerType mapping (computers-plugin domain).

The imaging pipeline writes C:\\Enrollment\\pc-type.txt (the gea-shopfloor-*
taxonomy). The collector maps that to a flask ComputerType. Defaults live here;
per-site overrides live in core Settings (pctypemap_<pxetype>, category
'pctypemapping') and are editable in the Settings UI. This indirection means
the imaging taxonomy can change without code edits.
"""

from shopdb.api import Setting

# pxe pc-type -> flask ComputerType name. Defaults; overridable via settings.
DEFAULT_PCTYPE_MAP = {
    'gea-shopfloor-collections': 'Shopfloor PC',
    'gea-shopfloor-nocollections': 'Shopfloor PC',
    'gea-shopfloor-common': 'Shopfloor PC',
    'gea-shopfloor-keyence': 'Shopfloor PC',
    'gea-shopfloor-cmm': 'CMM PC',
    'gea-shopfloor-genspect': 'Shopfloor PC',
    'gea-shopfloor-heattreat': 'Shopfloor PC',
    'gea-shopfloor-waxtrace': 'Shopfloor PC',
    'gea-shopfloor-display': 'Kiosk',
    'gea-shopfloor-partmarker': 'Shopfloor PC',
}

_SETTING_PREFIX = 'pctypemap_'
_SETTING_CATEGORY = 'pctypemapping'


def pctype_mapping():
    """Return the live pctype -> ComputerType-name map (settings over defaults)."""
    mapping = dict(DEFAULT_PCTYPE_MAP)
    for setting in Setting.query.filter_by(category=_SETTING_CATEGORY).all():
        if setting.key.startswith(_SETTING_PREFIX):
            mapping[setting.key[len(_SETTING_PREFIX):]] = setting.get_typed_value()
    return mapping


def seed_pctype_settings():
    """Seed the pctypemap_<pxetype> settings from defaults (idempotent)."""
    for pxetype, computertype in DEFAULT_PCTYPE_MAP.items():
        key = f'{_SETTING_PREFIX}{pxetype}'
        if not Setting.query.filter_by(key=key).first():
            Setting.set(key, computertype, valuetype='string',
                        category=_SETTING_CATEGORY,
                        description=f'Collector maps pc-type {pxetype} to this ComputerType')
