from pathlib import Path
from typing import Literal, Optional

from pydantic import model_validator, Field
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    """支持.env改写所有路径的配置类"""
    # 开发模式配置:
    # - "dev": pip install -e 可编辑安装，包安装到 <project>/.alaya.ai/...，可直接修改源码
    # - "dev-uneditable": pip install . 标准安装，包会安装到 site-package
    # - "prod":pip install alayaflow 部署模式，使用 ~/.alaya.ai/alayaflow
    dev_mode: Literal["dev", "dev-uneditable", "prod"] = "dev"

    def is_dev(self) -> bool:
        return self.dev_mode == "dev"

    def is_uneditable_dev(self) -> bool:
        return self.dev_mode == "dev-uneditable"

    def is_prod(self) -> bool:
        return self.dev_mode == "prod"
    
    alayaflow_root: Optional[Path] = None
    workspace_root: Optional[Path] = None
    resources_root: Optional[Path] = None
    workflow_storage_path: Optional[Path] = None

    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
    log_dir: Optional[Path] = None
    
    alayahub_url: str = "http://localhost:8000"

    # Langfuse 配置
    langfuse_enabled: bool = False
    langfuse_public_key: Optional[str] = ""
    langfuse_secret_key: Optional[str] = ""
    langfuse_base_url: Optional[str] = "http://100.64.0.34:4000/"
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore" 
    )

    @property
    def cache_dir(self) -> Path:
        return self.workspace_root / "cache"

    @property
    def envs_dir(self) -> Path:
        return self.workspace_root / "envs"

    @model_validator(mode="after")
    def set_default_paths(self):
        
        current_file = Path(__file__).absolute()
        project_root = current_file.parent.parent.parent.parent

        is_editable_install = (project_root / "pyproject.toml").exists() or (project_root / "setup.py").exists()

        if self.alayaflow_root is None:
            if self.is_dev() and is_editable_install:
                self.alayaflow_root = project_root
            else:
                self.alayaflow_root = current_file.parent.parent.parent
        else:
            # 将相对路径转换为绝对路径
            alayaflow_root_path = Path(self.alayaflow_root)
            if not alayaflow_root_path.is_absolute():
                # 如果是相对路径，相对于当前工作目录解析
                self.alayaflow_root = alayaflow_root_path.resolve()
            else:
                self.alayaflow_root = alayaflow_root_path

        if self.workspace_root is None:
            if self.is_dev() and is_editable_install:
                self.workspace_root = project_root / ".alaya.ai" / "alayaflow"
            else:
                self.workspace_root = Path.home() / ".alaya.ai" / "alayaflow"
        else:
            self.workspace_root = Path(self.workspace_root)

        if self.workflow_storage_path is None:
            self.workflow_storage_path = self.workspace_root / "workflows"
        else:
            self.workflow_storage_path = Path(self.workflow_storage_path)

        if self.log_dir is None:
            self.log_dir = self.workspace_root / "logs"
        else:
            self.log_dir = Path(self.log_dir)

        return self

    @model_validator(mode='after')
    def create_directories(self):
        """
        在配置加载（实例化）完成后，自动检查并创建必要的目录结构
        """
        self.workspace_root.mkdir(parents=True, exist_ok=True)
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        self.envs_dir.mkdir(parents=True, exist_ok=True)
        self.workflow_storage_path.mkdir(parents=True, exist_ok=True)
        
        return self

settings = Settings()
