"""
系统设置服务

负责加载、保存和管理全局系统设置。
"""
import json
import logging
from pathlib import Path
from typing import Optional

from core.config import settings
from models.system_settings import SystemSettings, DEFAULT_SYSTEM_SETTINGS

logger = logging.getLogger(__name__)


class SystemSettingsService:
    """
    系统设置服务
    
    提供设置的加载、保存和访问功能
    """
    
    def __init__(self):
        self.settings_file = settings.SYSTEM_SETTINGS_FILE
        self._settings: Optional[SystemSettings] = None
        self._load_settings()
    
    def _load_settings(self):
        """从文件加载系统设置"""
        if self.settings_file.exists():
            try:
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                self._settings = SystemSettings(**data)
                logger.info(f"加载系统设置成功")
            except Exception as e:
                logger.error(f"加载系统设置失败: {e}")
                self._settings = DEFAULT_SYSTEM_SETTINGS.copy()
        else:
            logger.info("系统设置文件不存在，使用默认设置")
            self._settings = DEFAULT_SYSTEM_SETTINGS.copy()
            self._save_settings()
    
    def _save_settings(self):
        """保存系统设置到文件"""
        try:
            # 确保父目录存在
            self.settings_file.parent.mkdir(parents=True, exist_ok=True)
            
            # 写入文件
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(self._settings.dict(), f, ensure_ascii=False, indent=2)
            
            logger.info(f"系统设置已保存到 {self.settings_file}")
        except Exception as e:
            logger.error(f"保存系统设置失败: {e}")
    
    @property
    def settings(self) -> SystemSettings:
        """获取当前系统设置"""
        return self._settings
    
    def update_thinking_tags(self, prefix: str, suffix: str):
        """更新思考标签配置"""
        self._settings.thinkingTagPrefix = prefix
        self._settings.thinkingTagSuffix = suffix
        self._settings.updatedAt = int(__import__('time').time())
        self._save_settings()
        logger.info(f"思考标签已更新: {prefix} ... {suffix}")
    
    def update_current_preset(self, preset_name: Optional[str]):
        """更新当前选中的预设名称"""
        self._settings.currentPresetName = preset_name
        self._settings.updatedAt = int(__import__('time').time())
        self._save_settings()
        logger.info(f"当前预设已更新: {preset_name}")
    
    def get_thinking_tag_pattern(self) -> str:
        """获取思考标签的正则表达式模式"""
        prefix = self._settings.thinkingTagPrefix
        suffix = self._settings.thinkingTagSuffix
        
        # 转义特殊字符
        import re
        escaped_prefix = re.escape(prefix)
        escaped_suffix = re.escape(suffix)
        
        # 返回匹配思考内容的正则模式
        return f"{escaped_prefix}[\\s\\S]*?{escaped_suffix}"


# 全局实例
system_settings_service = SystemSettingsService()
