from pathlib import Path
from typing import Literal, Optional
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict

PROJECT_DEV_ROOT = Path(__file__).resolve().parent.parent.parent.parent

def auto_infer_dev_mode():
    if (PROJECT_DEV_ROOT / "pyproject.toml").exists():
        return "dev"
    return "prod"

class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        extra="ignore",
    )

    dev_mode: Literal["dev", "prod"] = Field(
        default_factory=auto_infer_dev_mode,
        description="Development mode. Set to 'dev' to enable development features.",
    )

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

    ## Log ##

    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"

    ## Path settings ##

    # only available in dev mode
    project_dev_root: Path = PROJECT_DEV_ROOT

    root_dir: Optional[Path] = Path.home() / ".alaya.ai" / "alayaflow"

    workflows_dir: Optional[Path] = root_dir / "workflows"
    envs_dir: Optional[Path] = root_dir / "envs"
    logs_dir: Optional[Path] = root_dir / "logs"

    def set_root_dir(self, root_dir: Path | str):
        if isinstance(root_dir, str):
            root_dir = Path(root_dir)
        self.root_dir = root_dir
        self.workflows_dir = root_dir / "workflows"
        self.envs_dir = root_dir / "envs"
        self.logs_dir = root_dir / "logs"

    ## Service settings ##

    alayahub_url: str = "http://your-alayahub-url"
    alayahub_download_url: str = "http://your-alayahub-download-url"

    # 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/"

settings = Settings()