"""
ConfManClient - conf-man CLI封装
PM-Agent v2.0 - F-031

功能: 封装conf-man配置管理和环境查询接口
"""
import sys
import logging
import os
from pathlib import Path
from typing import Optional

logger = logging.getLogger(__name__)


class ConfManError(Exception):
    """conf-man调用异常基类"""
    pass


class ConfManNotFoundError(ConfManError):
    """conf-man模块未找到"""
    pass


class ConfManExecutionError(ConfManError):
    """conf-man执行失败"""
    pass


_conf_man_provider_class = None
_conf_man_env_class = None


def _set_conf_man_classes(provider_class, env_class):
    """设置conf-man类（用于测试）"""
    global _conf_man_provider_class, _conf_man_env_class
    _conf_man_provider_class = provider_class
    _conf_man_env_class = env_class


class ConfManClient:
    """conf-man配置管理客户端"""
    
    def __init__(self):
        """初始化ConfManClient"""
        self._provider = None
        self._env_config = None
        self._load_conf_man()
    
    def _load_conf_man(self):
        """加载conf-man模块"""
        global _conf_man_provider_class, _conf_man_env_class
        
        if _conf_man_provider_class is not None:
            try:
                self._provider = _conf_man_provider_class()
                self._env_config = _conf_man_env_class()
                logger.info("ConfManClient initialized with injected classes")
                return
            except Exception as e:
                logger.warning(f"Failed to use injected classes: {e}")
        
        try:
            conf_man_path = os.environ.get("CONF_MAN_PATH")
            if not conf_man_path:
                conf_man_path = str(Path(__file__).parent.parent.parent.parent / "conf-man" / "src")
            
            if not Path(conf_man_path).exists():
                logger.warning(f"conf-man path not found: {conf_man_path}")
                raise ImportError("conf-man not found")
            
            sys.path.insert(0, conf_man_path)
            from config_provider import ConfManProvider, get_provider
            from environment_config import EnvironmentConfig
            
            self._provider = get_provider()
            self._env_config = EnvironmentConfig()
            logger.info("ConfManClient initialized successfully")
        except ImportError as e:
            logger.warning(f"conf-man not available: {e}")
            self._provider = None
            self._env_config = None
    
    def _check_available(self):
        """检查conf-man是否可用"""
        if self._provider is None:
            raise ImportError("conf-man not available. Please ensure conf-man is installed.")
    
    def get_data_dir(self) -> str:
        """获取数据目录"""
        self._check_available()
        return self._provider.get_data_dir()
    
    def get_config_dir(self) -> str:
        """获取配置目录"""
        self._check_available()
        return self._provider.get_config_dir()
    
    def get_log_dir(self) -> str:
        """获取日志目录"""
        self._check_available()
        return self._provider.get_log_dir()
    
    def get_temp_dir(self) -> str:
        """获取临时目录"""
        self._check_available()
        return self._provider.get_temp_dir()
    
    def get_todo_db_path(self) -> str:
        """获取TODO数据库路径"""
        self._check_available()
        return self._provider.get_todo_db_path()
    
    def get_state_file_path(self) -> str:
        """获取状态文件路径"""
        self._check_available()
        return self._provider.get_state_file_path()
    
    def get_lock_file_path(self, name: str) -> str:
        """获取锁文件路径"""
        self._check_available()
        return self._provider.get_lock_file_path(name)
    
    def get_agent_status_db_path(self) -> str:
        """获取Agent状态数据库路径"""
        self._check_available()
        return self._provider.get_agent_status_db_path()
    
    def get_session_dir(self) -> str:
        """获取会话目录"""
        self._check_available()
        return self._provider.get_session_dir()
    
    def get_adhoc_todos_path(self) -> str:
        """获取临时TODO文件路径"""
        self._check_available()
        return self._provider.get_adhoc_todos_path()
    
    def get_identity_file_path(self) -> str:
        """获取身份文件路径"""
        self._check_available()
        return self._provider.get_identity_file_path()
    
    def get_pid_file_path(self) -> str:
        """获取PID文件路径"""
        self._check_available()
        return self._provider.get_pid_file_path()
    
    def get_opencode_db_path(self) -> str:
        """获取opencode数据库路径"""
        self._check_available()
        return self._provider.get_opencode_db_path()
    
    def get_agents_config_path(self) -> str:
        """获取Agent配置路径"""
        self._check_available()
        return self._provider.get_agents_config_path()
    
    def get_git_sync_config_path(self) -> str:
        """获取Git同步配置路径"""
        self._check_available()
        return self._provider.get_git_sync_config_path()
    
    def get_notification_config_path(self) -> str:
        """获取通知配置路径"""
        self._check_available()
        return self._provider.get_notification_config_path()
    
    def get_skill_index_path(self) -> str:
        """获取Skill索引路径"""
        self._check_available()
        return self._provider.get_skill_index_path()
    
    def get_file_owners_path(self) -> str:
        """获取文件所有者配置路径"""
        self._check_available()
        return self._provider.get_file_owners_path()
    
    def get_full_path(self, relative_path: str) -> Path:
        """获取完整路径"""
        self._check_available()
        return self._provider.get_full_path(relative_path)
    
    def get_version(self) -> str:
        """获取conf-man版本"""
        self._check_available()
        return self._provider.get_version()
    
    def get_environment(self) -> str:
        """获取当前环境"""
        self._check_available()
        return self._env_config.get_environment()
    
    def is_test_mode(self) -> bool:
        """检查是否为测试模式"""
        self._check_available()
        return self._env_config.is_test_mode()
    
    def is_available(self) -> bool:
        """检查conf-man是否可用"""
        return self._provider is not None and self._env_config is not None
