# -*- coding: utf-8 -*-
"""
container.py — 依赖容器

集中持有单例与配置，解决原 server.py 中模块级全局变量散布、跨模块单例重置
（rebuild_search_index 的 global search_engine）等副作用问题。

设计原则：
  - 单向依赖：services / routes 单向 import container，container 不反向依赖它们
  - 懒加载：所有单例首次访问才初始化
  - 可重置：search_engine 提供 reset_search_engine()，供 record_service 重建索引后调用

从原 server.py 迁入（行为保持不变）：load_config / config / get_search_engine
/ get_safety_filter / get_cache_manager / get_skill_md
"""

import os
import json
from pathlib import Path

from utils.paths import SCRIPT_DIR, CONFIG_FILE
from utils.logger import get_logger

logger = get_logger(__name__)


# ============================================================
# 配置
# ============================================================

def load_config():
    """加载配置文件"""
    if CONFIG_FILE.exists():
        with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {
        "claude_api_base": os.environ.get("CLAUDE_API_BASE", ""),
        "claude_api_key": os.environ.get("CLAUDE_API_KEY", ""),
        "claude_model": "claude-sonnet-4-6",
        "embedding_enabled": True,
        "embedding_model": "text-embedding-3-small",
        "embedding_api_timeout": 10,
        "system_types": [
            {"value": "std20", "label": "标准版预定2.0"},
            {"value": "ops", "label": "标准版运维集控系统"},
            {"value": "new_unified", "label": "新统一平台"},
            {"value": "unified", "label": "统一平台"},
        ],
    }


_config = None

def get_config():
    """获取配置（懒加载单例）"""
    global _config
    if _config is None:
        _config = load_config()
    return _config


# ============================================================
# 单例（懒加载）
# ============================================================

_search_engine = None

def get_search_engine():
    """获取搜索引擎实例"""
    global _search_engine
    if _search_engine is None:
        from search_engine import SearchEngine
        _search_engine = SearchEngine()
    return _search_engine

def reset_search_engine():
    """重置搜索引擎单例（供 record_service.rebuild_search_index 调用，强制下次重建索引）"""
    global _search_engine
    _search_engine = None


_safety_filter = None

def get_safety_filter():
    """获取安全过滤器模块"""
    global _safety_filter
    if _safety_filter is None:
        import safety_filter as sf
        _safety_filter = sf
    return _safety_filter


_cache_manager = None

def get_cache_manager():
    """获取缓存管理器实例"""
    global _cache_manager
    if _cache_manager is None:
        from cache_manager import CacheManager
        cache_dir = SCRIPT_DIR / "cache"
        _cache_manager = CacheManager(cache_dir, expire_hours=24)
    return _cache_manager


# ============================================================
# SKILL.md（懒加载，带缓存标志）
# ============================================================

_SKILL_MD = None
_SKILL_MD_LOADED = False

def get_skill_md():
    """加载 Troubleshoot SKILL.md — 按优先级查找（部署环境 → 开发环境）"""
    global _SKILL_MD, _SKILL_MD_LOADED
    if _SKILL_MD_LOADED:
        return _SKILL_MD
    _SKILL_MD_LOADED = True

    # 路径优先级（部署环境 → 开发环境 → 备用）
    skill_paths = [
        Path("/opt/troubleshoot/SKILL.md"),           # 部署环境（优先）
        SCRIPT_DIR.parent / "SKILL.md",               # 开发环境：code/SKILL.md
        SCRIPT_DIR.parent.parent / "SKILL.md",        # 备用：skills/Troubleshoot/SKILL.md
    ]

    for skill_file in skill_paths:
        if skill_file.exists():
            _SKILL_MD = skill_file.read_text(encoding='utf-8')
            # 只保留排查套路部分（不包含 frontmatter）
            if '---' in _SKILL_MD:
                parts = _SKILL_MD.split('---', 2)
                if len(parts) >= 3:
                    _SKILL_MD = parts[2].strip()
            print(f"[SKILL.md] 已加载：{skill_file}")
            return _SKILL_MD

    _SKILL_MD = ""
    print("[SKILL.md] 警告：未找到 SKILL.md 文件")
    return _SKILL_MD
