from pypos.core.utils.scanner_device_utils import extract_device_match_token, normalize_device_name


class ScannerPairingService:
    def normalize_discovered_devices(self, raw_devices):
        rows = raw_devices if isinstance(raw_devices, list) else []
        result = []
        seen = set()
        for row in rows:
            name = ""
            token = ""
            if isinstance(row, dict):
                name = normalize_device_name(row.get("name"))
                token = str(row.get("token") or "").strip().lower()
            else:
                name = normalize_device_name(row)
            if not name:
                continue
            if not token:
                token = extract_device_match_token(name)
            key = (name.lower(), token)
            if key in seen:
                continue
            seen.add(key)
            result.append({"name": name, "token": token})
        return result

    def append_token_to_whitelist(self, current_whitelist, token):
        values = current_whitelist if isinstance(current_whitelist, list) else []
        cleaned = []
        seen = set()
        for value in values:
            text = str(value or "").strip().lower()
            if not text or text in seen:
                continue
            cleaned.append(text)
            seen.add(text)
        token_text = str(token or "").strip().lower()
        if token_text and token_text not in seen:
            cleaned.append(token_text)
        return cleaned

    def pair_device(self, current_settings, selected_device, replace=False):
        settings = current_settings if isinstance(current_settings, dict) else {}
        selected = selected_device if isinstance(selected_device, dict) else {}
        device_name = normalize_device_name(selected.get("name"))
        token = str(selected.get("token") or "").strip().lower()
        if not token and device_name:
            token = extract_device_match_token(device_name)
        if not token:
            return None
        if bool(replace):
            next_whitelist = [token]
        else:
            next_whitelist = self.append_token_to_whitelist(
                settings.get("rawinput_whitelist"),
                token,
            )
        payload = dict(settings)
        payload["rawinput_whitelist"] = next_whitelist
        if "rawinput_enabled" not in payload:
            payload["rawinput_enabled"] = True
        if "backend_mode" not in payload:
            payload["backend_mode"] = "auto"
        return payload
