from pathlib import Path
from typing import Any, Optional

from pydantic_settings import BaseSettings

from mineru_flow.internal.common.io import get_data_dir
from mineru_flow.internal.common.logging import get_logger

_data_dir = Path(get_data_dir()).resolve()
_media_dir = _data_dir / "media"
_artifacts_dir = _media_dir / "artifacts"
_media_dir.mkdir(parents=True, exist_ok=True)
_artifacts_dir.mkdir(parents=True, exist_ok=True)

data_dir = str(_data_dir)
media_dir = str(_media_dir)
artifacts_dir = str(_artifacts_dir)

_config_logger = get_logger("config")


class Settings(BaseSettings):
    HOST: str = "0.0.0.0"
    PORT: str = "8001"

    BASE_DATA_DIR: str = data_dir
    DATABASE_URL: str | None = None
    LOG_LEVEL: str = "INFO"
    LOG_JSON: bool = False
    LOG_FILE: Optional[str] = None

    def model_post_init(self, __context: Any) -> None:
        db_name = "mineru_flow.sqlite"
        base_dir = Path(self.BASE_DATA_DIR).expanduser()
        base_dir.mkdir(parents=True, exist_ok=True)
        db_path = base_dir / db_name
        db_url = f"sqlite:///{db_path.as_posix()}"

        if not self.DATABASE_URL:
            self.DATABASE_URL = db_url

        _config_logger.info(
            "数据库配置已初始化",
            database_url=self.DATABASE_URL,
            base_data_dir=str(base_dir),
        )
        _config_logger.debug(
            "日志配置",
            log_level=self.LOG_LEVEL,
            log_json=self.LOG_JSON,
            log_file=self.LOG_FILE,
        )

    class Config:
        env_prefix = ""
        env_file_encoding = "utf-8"
        case_sensitive = True


settings = Settings()
