""" Persistence for the PT-E560BT label layout settings. Stored as JSON next to the application so the operator's logo, static text and QR template survive restarts. Kept deliberately tolerant: a missing or corrupt file silently yields defaults rather than blocking printing. """ from __future__ import annotations import json import os from ptouch_label import LabelConfig CONFIG_FILENAME = "label_config.json" def config_path(base_dir: str | None = None) -> str: """Absolute path to the settings file.""" directory = base_dir or os.path.dirname(os.path.abspath(__file__)) return os.path.join(directory, CONFIG_FILENAME) def load_config(base_dir: str | None = None) -> LabelConfig: """Load settings, falling back to defaults when absent or unreadable.""" path = config_path(base_dir) if not os.path.exists(path): return LabelConfig() try: with open(path, "r", encoding="utf-8") as handle: return LabelConfig.from_dict(json.load(handle)) except (OSError, ValueError) as exc: print(f"Could not read {CONFIG_FILENAME} ({exc}); using defaults.") return LabelConfig() def save_config(config: LabelConfig, base_dir: str | None = None) -> str: """Write settings to disk and return the path written.""" path = config_path(base_dir) with open(path, "w", encoding="utf-8") as handle: json.dump(config.to_dict(), handle, indent=2, ensure_ascii=False) return path