"""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',
}

# DEPRECATED settings surface: the "Collector PC Types" settings page is retired
# (GE-Enforce scope computertypeid supersedes it, ADR-012). Collector still reads
# this map, so keep the code; only the editor UI card is gone.
_SETTING_PREFIX = 'pctypemap_'
_SETTING_CATEGORY = 'pctypemapping'

# Metrology imaging pc-types: the PC itself stays a shopfloor PC, but it drives
# an attached measuring instrument. When the collector sees one of these, it
# auto-creates a MeasuringTool asset for the device and links the PC to it with
# a "controls" relationship (see ComputersPlugin._sync_measuringtool_link).
# Maps imaging pc-type -> (MeasuringToolType name, type description). The type
# is created on demand if the measuringtools plugin has not seeded it.
METROLOGY_TOOL_MAP = {
    'gea-shopfloor-cmm': ('CMM', 'Coordinate measuring machine'),
    'gea-shopfloor-keyence': ('Vision System', 'Optical / vision measurement system (Keyence)'),
    'gea-shopfloor-genspect': ('Genspect', 'Genspect visual / borescope inspection system'),
    'gea-shopfloor-waxtrace': ('Form Tracer', 'Surface / form tracing system (wax and trace)'),
}


# Imaging pc-type for a PC that drives a Telesis part marker. The marker is its
# own asset, not a field on the PC: several markers can serve one operation
# number (0613, 0615, WJPRT all have more than one), so filing their configs
# under the operation collapsed separate devices into one record. One marker per
# PC, so the PC identifies the marker - the same shape as METROLOGY_TOOL_MAP.
PARTMARKER_PCTYPE = 'gea-shopfloor-partmarker'

# MachineType a collector-created marker is given.
PARTMARKER_TYPENAME = 'Part Marker'


def drives_partmarker(pctype):
    """True when this imaging pc-type means the PC drives a part marker."""
    return (pctype or '').strip() == PARTMARKER_PCTYPE


def metrology_tool_for(pctype):
    """Return (typename, typedescription) if this pc-type drives a measuring
    tool, else None."""
    return METROLOGY_TOOL_MAP.get((pctype or '').strip())


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')
