import os
import json
import threading

CONFIG_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config')
CONFIG_FILE = os.path.join(CONFIG_DIR, 'config.json')

DEFAULT_CONFIG = {
    "enabled": True,
    "timezone": "Asia/Dhaka",
    "reply_once": True,
    "reply_after_hours": 24,
    "typing_delay": 3,
    "random_delay_min": 1,
    "random_delay_max": 3,
    "forward_enabled": False,
    "forward_target": "saved_messages",  # 'saved_messages', channel/group ID or username
    "tg_api_id": "",
    "tg_api_hash": "",
    "tg_phone": "",
    "tg_notification_enabled": False,
    "email_notification_enabled": False,
    "smtp_server": "",
    "smtp_port": 587,
    "smtp_user": "",
    "smtp_pass": "",
    "smtp_recipient": "",
    "desktop_notification_enabled": False,
    "site_name": "TG Auto Reply Pro",
    "theme": "dark",
    "primary_color": "#0d6efd",
    "footer_text": "© 2026 TG Auto Reply Pro. All Rights Reserved.",
    "logo_path": "",
    "favicon_path": "",
    "installed": False
}

class ConfigManager:
    _lock = threading.Lock()
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(ConfigManager, cls).__new__(cls)
            cls._instance.config = {}
            cls._instance.load()
        return cls._instance

    def load(self):
        with self._lock:
            if not os.path.exists(CONFIG_DIR):
                os.makedirs(CONFIG_DIR, exist_ok=True)
            
            if os.path.exists(CONFIG_FILE):
                try:
                    with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                        data = json.load(f)
                        # Ensure all default keys exist
                        self.config = {**DEFAULT_CONFIG, **data}
                except Exception as e:
                    print(f"Error loading config file: {e}")
                    self.config = DEFAULT_CONFIG.copy()
            else:
                self.config = DEFAULT_CONFIG.copy()
                self._save_unlocked()

    def get(self, key, default=None):
        with self._lock:
            return self.config.get(key, default)

    def set(self, key, value):
        with self._lock:
            self.config[key] = value
            self._save_unlocked()

    def update(self, new_settings):
        with self._lock:
            self.config.update(new_settings)
            self._save_unlocked()

    def save(self):
        with self._lock:
            self._save_unlocked()

    def _save_unlocked(self):
        try:
            if not os.path.exists(CONFIG_DIR):
                os.makedirs(CONFIG_DIR, exist_ok=True)
            with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=4, ensure_ascii=False)
        except Exception as e:
            print(f"Error saving config file: {e}")

    def get_all(self):
        with self._lock:
            return self.config.copy()
