from functools import lru_cache
from pathlib import Path

from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    app_name: str = "大本营答疑资产后台系统 MVP"
    database_url: str | None = Field(default=None, alias="DATABASE_URL")
    openai_api_key: str | None = Field(default=None, alias="OPENAI_API_KEY")
    openai_base_url: str | None = Field(default=None, alias="OPENAI_BASE_URL")
    model_name: str = Field(default="gpt-4.1-mini", alias="MODEL_NAME")

    feishu_app_id: str | None = Field(default=None, alias="FEISHU_APP_ID")
    feishu_app_secret: str | None = Field(default=None, alias="FEISHU_APP_SECRET")
    feishu_app_token: str | None = Field(default=None, alias="FEISHU_APP_TOKEN")
    feishu_wiki_node_token: str | None = Field(default=None, alias="FEISHU_WIKI_NODE_TOKEN")
    feishu_table_id_session: str | None = Field(default=None, alias="FEISHU_TABLE_ID_SESSION")
    feishu_table_id_raw_qa: str | None = Field(default=None, alias="FEISHU_TABLE_ID_RAW_QA")
    feishu_table_id_standard_qa: str | None = Field(default=None, alias="FEISHU_TABLE_ID_STANDARD_QA")

    schedule_cron: str = Field(default="0 1 * * *", alias="SCHEDULE_CRON")
    schedule_timezone: str = Field(default="Asia/Shanghai", alias="SCHEDULE_TIMEZONE")
    mock_mode: bool = Field(default=True, alias="MOCK_MODE")

    model_config = SettingsConfigDict(
        env_file=(".env", "../.env", "../../.env"),
        env_file_encoding="utf-8",
        extra="ignore",
        populate_by_name=True,
    )

    @property
    def resolved_database_url(self) -> str:
        if self.database_url:
            return self.database_url
        db_path = Path(__file__).resolve().parents[2] / "hy_qa_asset.db"
        return f"sqlite:///{db_path.as_posix()}"

    @property
    def openai_configured(self) -> bool:
        return bool(self.openai_api_key)

    @property
    def feishu_configured(self) -> bool:
        return all(
            [
                self.feishu_app_id,
                self.feishu_app_secret,
                self.feishu_app_token or self.feishu_wiki_node_token,
                self.feishu_table_id_session,
                self.feishu_table_id_raw_qa,
                self.feishu_table_id_standard_qa,
            ]
        )


@lru_cache
def get_settings() -> Settings:
    return Settings()
