from dataclasses import dataclass
import os
import logging

try:  # pragma: no cover - optional convenience
    from dotenv import load_dotenv  # type: ignore
    load_dotenv()
except Exception:
    pass

@dataclass
class Settings:
    default_wpm: int = 200
    openai_api_key: str | None = os.getenv("OPENAI_API_KEY")
    llm_model: str | None = os.getenv("GRANULE_LLM_MODEL")
    llm_provider: str | None = os.getenv("GRANULE_LLM_PROVIDER")
    llm_max_retries: int = int(os.getenv("GRANULE_LLM_MAX_RETRIES", "2") or 2)
    llm_min_interval_s: float = float(os.getenv("GRANULE_LLM_MIN_INTERVAL_S", "0"))  # min seconds between LLM calls
    adapt_rate_limits: bool = bool(
        1
        if os.getenv("GRANULE_LLM_ADAPT_RATE_LIMIT", "1").strip().lower() in {"1", "true", "yes", "y", "on"}
        else 0
    )
    disable_question_expand: bool = bool(
        1
        if os.getenv("GRANULE_LLM_DISABLE_QUESTION_EXPAND", "").strip().lower() in {"1", "true", "yes", "y", "on"}
        else 0
    )
    suppress_problem_questions: bool = bool(
        1
        if os.getenv("GRANULE_SUPPRESS_PROBLEM_QUESTIONS", "").strip().lower()
        in {"1", "true", "yes", "y", "on"}
        else 0
    )
    debug: bool = bool(
        1
        if os.getenv("GRANULE_DEBUG", "").strip().lower() in {"1", "true", "yes", "y", "on"}
        else 0
    )

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


# Initialize logging level once based on debug flag (idempotent if imported multiple times)
_log = logging.getLogger("granule")
if not _log.handlers:
    logging.basicConfig(level=logging.DEBUG if os.getenv("GRANULE_DEBUG") else logging.INFO,
                        format="%(asctime)s %(levelname)s %(name)s - %(message)s")

settings = Settings()
