"""Compatibility adapter for the canonical system identity file.""" from __future__ import annotations import json import os import tempfile from pathlib import Path from typing import Any from bfos.operations import dealer_is_valid from bfos.identity import DEALER_ID_FILE, identity_for, read_dealer_id PREFERENCES_FILENAME = "blueforce-gui.json" def preferences_path() -> Path: return Path(os.environ.get("BF_DEALER_ID_FILE", str(DEALER_ID_FILE))) def load_preferences(path: Path | None = None) -> dict[str, str]: target = path or preferences_path() if path is None: try: return identity_for(read_dealer_id(target)) except (OSError, ValueError): return {} try: data: Any = json.loads(target.read_text(encoding="utf-8")) except (OSError, ValueError): return {} if not isinstance(data, dict): return {} dealer = str(data.get("dealer_id", "")).strip() if not dealer_is_valid(dealer): return {} return identity_for(dealer) def save_dealer(dealer_id: str, path: Path | None = None) -> dict[str, str]: if not dealer_is_valid(dealer_id): raise ValueError("Bayi numarası tam 8 rakam olmalıdır.") target = path or preferences_path() identity = identity_for(dealer_id) if path is None and target.exists(): existing = read_dealer_id(target) if existing != dealer_id: raise PermissionError( f"Bayi kimliği {existing} olarak kilitli; değiştirmek için açık geçiş gerekir." ) if path is None: target.parent.mkdir(parents=True, exist_ok=True) fd, temporary_name = tempfile.mkstemp(prefix="dealer-id.", dir=str(target.parent)) try: os.fchmod(fd, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: handle.write(dealer_id + "\n") os.replace(temporary_name, target) finally: if os.path.exists(temporary_name): os.unlink(temporary_name) return identity target.parent.mkdir(parents=True, exist_ok=True) data = {"dealer_id": dealer_id, "active_user": f"bf-{dealer_id}"} temporary = target.with_suffix(target.suffix + ".tmp") temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") os.replace(temporary, target) return identity def clear_dealer(path: Path | None = None) -> None: target = path or preferences_path() try: target.unlink() except FileNotFoundError: pass