import json
import logging
import os
from pathlib import Path

logger = logging.getLogger(__name__)


class ConfigManager:
    DEFAULT_CONFIG = {
        "isDark": True,
        "isPinned": False,
        "triggerKey": "Ctrl",
        "defaultLang": "zh-CN",
        "translationMode": "mirror",
    }

    def __init__(self, config_dir: Path):
        self.config_dir = config_dir
        self.config_dir.mkdir(parents=True, exist_ok=True)
        self.path = self.config_dir / "config.json"
        self.config = self.DEFAULT_CONFIG.copy()
        self.load()

    def load(self):
        if not self.path.exists():
            self.save()
            return

        try:
            with open(self.path, encoding="utf-8") as f:
                loaded = json.load(f)
                for key in self.DEFAULT_CONFIG:
                    if key in loaded:
                        self.config[key] = loaded[key]
        except (OSError, json.JSONDecodeError) as e:
            logger.warning(f"Config file corrupted, resetting to defaults. Error: {e}")
            self.config = self.DEFAULT_CONFIG.copy()
            self.save()

    def save(self):
        try:
            with open(self.path, "w", encoding="utf-8") as f:
                json.dump(self.config, f, indent=4)
        except OSError as e:
            logger.error(f"Error saving config: {e}")

    def get(self, key):
        return self.config.get(key, self.DEFAULT_CONFIG.get(key))

    def set(self, key, value):
        if self.config.get(key) != value:
            self.config[key] = value
            self.save()
