"""تنظیمات مرکزی پروژه — همه مقادیر از فایل .env خوانده می‌شوند."""

from __future__ import annotations

import os
import re
from functools import lru_cache
from pathlib import Path

from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

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

# نگاشت شناسه ایجنت به دیتابیس Notion (نام‌های داخل .env)
NOTION_DB_FIELDS: dict[str, str] = {
    "AG01": "notion_db_market",
    "AG02": "notion_db_copy",
    "AG03": "notion_db_content",
    "AG04": "notion_db_design",
    "AG05": "notion_db_web",
    "AG06": "notion_db_seo",
    "AG07": "notion_db_data",
    "AG08": "notion_db_campaign",
}


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=os.getenv("ENV_FILE") or str(BASE_DIR / ".env"),
        env_file_encoding="utf-8",
        extra="ignore",
        case_sensitive=False,
    )

    #: نسخهٔ سامانه
    app_version: str = "1.0.2-beta"

    # ---------- Telegram ----------
    telegram_bot_token: str = ""
    telegram_webhook_secret: str = "change-me-secret"
    webhook_path: str = "/telegram/webhook"
    public_base_url: str = "https://example.com"  # دامنه‌ای که FastAPI روی آن سرو می‌شود
    drop_pending_updates: bool = False
    host: str = "0.0.0.0"
    port: int = 8080

    # ---------- OpenAI ----------
    openai_api_key: str = ""
    openai_model: str = "gpt-4o"
    openai_temperature: float = 0.4
    openai_max_tokens: int = 2000
    openai_timeout: float = 90.0

    # ---------- MongoDB ----------
    mongodb_uri: str = "mongodb://localhost:27017"
    mongodb_db: str = "tg_agents"
    chat_history_collection: str = "chat_history"

    # ---------- Notion ----------
    notion_api_key: str = ""
    notion_api_version: str = "2022-06-28"
    notion_records_limit: int = 10
    notion_status_property: str = "Status"
    notion_status_active_value: str = "فعال"
    notion_daily_log_db: str = ""
    # نام پراپرتی‌های دیتابیس daily_log (اگر اسکیمای شما فرق دارد اینجا عوض کنید)
    notion_daily_log_agent_prop: str = "Agent"
    notion_daily_log_mission_prop: str = "Mission"
    notion_daily_log_date_prop: str = "Date"
    notion_daily_log_evidence_prop: str = "Evidence"

    notion_db_market: str = ""
    notion_db_copy: str = ""
    notion_db_content: str = ""
    notion_db_design: str = ""
    notion_db_web: str = ""
    notion_db_seo: str = ""
    notion_db_data: str = ""
    notion_db_campaign: str = ""

    # ---------- گیرندگان وظیفه: ۹ ایجنت + ۳ انسان ----------
    #: نام و نقش انسان‌ها — قالب: «H01=علی:مدیر پروژه,H02=رضا:مالک ایجنت‌ها»
    human_names: str = ""
    #: شناسه‌های تلگرام هر انسان (برای اتصال خودکار «من کی هستم»)
    human_h01_ids: str = ""
    human_h02_ids: str = ""
    human_h03_ids: str = ""
    human_h01_usernames: str = ""
    human_h02_usernames: str = ""
    human_h03_usernames: str = ""
    #: شناسهٔ کاربر Notion هر انسان (برای منشن واقعی در Notion)
    human_h01_notion_user: str = ""
    human_h02_notion_user: str = ""
    human_h03_notion_user: str = ""
    #: دستور وظیفه چه پیشوندهایی داشته باشد
    task_command_aliases: str = "task,ta,assign,وظیفه,کار"
    #: اگر true باشد، یک /task با چند گیرنده = یک وظیفه برای هر گیرنده
    task_multi_split: bool = True
    #: وظیفهٔ انسانی خودکار «منتظر بازبینی» ثبت شود یا «برای انجام»
    human_task_status: str = "todo"
    #: پولر، وظایف انسانی را هم اسکن کند (فقط برای اعلان، اجرا نمی‌کند)
    human_notify_on_poll: bool = True

    # ---------- منابع دادهٔ موجود (فقط‌خواندنی) ----------
    #: بانک مرکزی وظایف (منبع حقیقت وظایف)
    notion_db_tasks: str = ""
    #: شناسنامه‌های شغلی
    notion_db_roles: str = ""
    #: خطوط درآمدی
    notion_db_revenue: str = ""
    #: سقف رکورد خوانده‌شده از هر منبع در هر درخواست
    sources_max_records: int = 25
    #: قالب‌بندی هر رکورد برای پرامپت (اگر false فقط عنوان و چند فیلد کلیدی)
    sources_full_fields: bool = True

    # ---------- Google Sheets (از طریق n8n) ----------
    #: توکن مشترک برای اندپوینت داخلی /internal/sheets/push
    internal_token: str = ""
    #: اگر true، پوش Sheets از هر IP پذیرفته می‌شود (پیش‌فرض: فقط loopback)
    sheets_push_allow_remote: bool = False
    #: منبع حقیقت وظایف: central | local
    tasks_source: str = "central"

    # ---------- دیتابیس وظایف و اتوماسیون زنجیره‌ای ----------
    # دیتابیس Tasks در Notion (اسکریپت setup_notion.py می‌سازد)
    notion_tasks_db: str = ""
    # نام پراپرتی‌های دیتابیس Tasks (اگر اسکیمای شما فرق دارد عوض کنید)
    notion_task_title_prop: str = "Name"
    notion_task_assignee_prop: str = "Assignee"
    notion_task_status_prop: str = "Status"
    notion_task_priority_prop: str = "Priority"
    notion_task_description_prop: str = "Description"
    notion_task_result_prop: str = "Result"
    notion_task_evidence_prop: str = "Evidence"
    notion_task_parent_prop: str = "ParentTask"
    notion_task_source_prop: str = "Source"
    notion_task_chatid_prop: str = "ChatID"
    notion_task_requester_prop: str = "Requester"
    notion_task_trace_prop: str = "TraceID"
    notion_task_created_prop: str = "Created"

    # نام واقعی گزینه‌های Status در دیتابیس شما
    # (tools/notion_map.py این‌ها را خودکار پر می‌کند)
    notion_task_status_todo: str = "برای انجام"
    notion_task_status_doing: str = "در حال انجام"
    notion_task_status_review: str = "منتظر بازبینی"
    notion_task_status_done: str = "انجام شد"
    notion_task_status_blocked: str = "مسدود"
    notion_task_status_rejected: str = "رد شد"
    notion_task_status_backlog: str = "بک‌لاگ"
    # پولر Notion: هر چند ثانیه وظایف جدید را بخواند
    notion_poll_seconds: int = 30
    notion_poller_enabled: bool = True
    # اگر true باشد، نتیجهٔ ایجنت خودکار «انجام شد» می‌شود (بدون تأیید مدیر)
    # پیش‌فرض false: نتیجه به «منتظر بازبینی» می‌رود و مدیر تأیید می‌کند
    tasks_auto_close: bool = False
    # حداکثر تعداد زیرکار در یک زنجیره (محافظت از هزینهٔ توکن)
    tasks_max_subtasks: int = 8

    # ---------- کنترل دسترسی و ویزارد راه‌اندازی ----------
    # شناسه‌های عددی کاربرانی که مجاز به /start و تنظیمات در پیوی هستند (با کاما جدا کنید)
    telegram_allowed_user_ids: str = ""
    # نام‌کاربری‌های مجاز (بدون @، با کاما)
    telegram_allowed_usernames: str = ""
    # اگر true باشد، ایجنت‌ها در گروه هم فقط برای همین کاربران پاسخ می‌دهند
    allowed_users_strict: bool = False

    # ---------- نقش‌های سه‌گانهٔ گروه ----------
    # مالک ایجنت‌ها (برادر): تنظیمات + ساخت وظیفه + همهٔ ایجنت‌ها
    #   اگر خالی باشد، همان فهرست ادمین‌ها استفاده می‌شود
    # ---------- منشن = وظیفه ----------
    # off   → منشن فقط پاسخ فوری می‌دهد (پیش‌فرض)
    # all   → هر منشن در Notion وظیفه می‌شود
    # task  → فقط اگر «وظیفه/task» در پیام باشد
    # reply → فقط اگر ریپلای باشد
    # ---------- ارائه‌دهندهٔ LLM ----------
    # offline | openai | groq | gemini | openrouter | deepseek | ollama | custom
    # offline = بدون هیچ کلیدی، پاسخ قاعده‌محور از داده‌های واقعی
    llm_provider: str = "openai"
    #: اگر پر باشد بر آدرس پیش‌فرض ارائه‌دهنده اولویت دارد
    llm_base_url: str = ""
    #: کلیدهای رایگان ارائه‌دهنده‌های دیگر (اختیاری)
    groq_api_key: str = ""
    gemini_api_key: str = ""
    openrouter_api_key: str = ""
    deepseek_api_key: str = ""

    # ---------- اتوماسیون Notion (بدون تلگرام) ----------
    #: دیتابیس «Inbox» — هر ردیف یک درخواست؛ پاسخ در همان صفحه کامنت می‌شود
    notion_inbox_db: str = ""
    #: صفحه‌هایی که کامنت‌هایشان رصد شود (با کاما جدا شود)
    notion_watch_pages: str = ""
    #: اگر فهرست بالا خالی بود، این تعداد صفحهٔ اخیر جست‌وجو شود
    notion_watch_recent: int = 25
    #: بازهٔ اسکن (ثانیه)
    notion_native_interval: int = 45
    notion_native_enabled: bool = False
    #: نگاشت UUID کاربر Notion → کد ایجنت:  «uuid1:AG04,uuid2:AG03»
    notion_user_agent_map: str = ""
    #: نگاشت ایجنت → کاربر/صفحهٔ Notion برای نوشتن منشن واقعی:
    #: «AG03=<uuid>,AG04=page:<uuid>»  (خالی = متن سادهٔ @AG03)
    notion_agent_users: str = ""
    #: پراپرتی‌های تاپیک در دیتابیس Tasks
    notion_task_topic_prop: str = "Topic"
    notion_task_link_prop: str = "Link"
    #: همهٔ پاسخ‌ها را قبل از نوشتن نمایش بده (اجرای آزمایشی)
    notion_native_dry_run: bool = False

    mention_task_mode: str = "off"
    #: متن کوتاه‌تر از این نادیده گرفته می‌شود (جلوگیری از «@ag01؟»)
    mention_task_min_chars: int = 12
    #: سقف وظیفه در ساعت (۰ = بی‌نهایت) — کنترل هزینه
    mention_task_max_per_hour: int = 20

    telegram_owner_ids: str = ""
    telegram_owner_usernames: str = ""
    # کاربران عادی: فقط خواندن (می‌توانند ایجنت را صدا بزنند ولی وظیفه نسازند)
    #   اگر TASK_CREATORS_STRICT=true، فقط مالک/ادمین (یا سازندگان فهرست‌شده)
    #   می‌توانند /task بزنند. پیش‌فرض true چون در گروه، کارفرما نباید
    #   بتواند وظیفه بسازد — فقط برادر/مدیر.
    task_creators_strict: bool = True
    telegram_task_creator_ids: str = ""
    telegram_task_creator_usernames: str = ""
    #: ادمین‌ها همه‌کاره‌اند (اگر مالک تنظیم نشده باشد)
    # نمایش ویزارد راه‌اندازی در پیوی
    setup_wizard_enabled: bool = True
    # ذخیره تنظیمات واردشده در ویزارد (در MongoDB، collection مربوطه)
    setup_store_collection: str = "bot_config"
    mongo_config_collection: str = "bot_config"

    # ---------- رفتار ----------
    history_limit: int = 30
    display_timezone: str = "Asia/Tehran"
    max_reply_chars: int = 3900
    agent_delay_seconds: float = 0.8  # فاصله بین پاسخ ایجنت‌ها در حالت /all
    log_level: str = "INFO"

    @field_validator("public_base_url", "webhook_path", mode="before")
    @classmethod
    def _clean_url(cls, value: object) -> object:
        """پاک‌سازی مقادیر کپی‌شده از ادیتور/Markdown: [url](url) یا [url] یا فاصله."""
        if not isinstance(value, str):
            return value
        text = value.strip()
        match = re.match(r"^\[(?P<a>[^\]]+)\]\((?P<b>[^)]+)\)$", text)
        if match:
            text = match.group("b") or match.group("a")
        elif text.startswith("[") and text.endswith("]"):
            text = text[1:-1]
        return text.strip()

    # ---------- مشتقات ----------
    def allowed_ids(self) -> set[int]:
        return {int(x) for x in self.telegram_allowed_user_ids.replace(";", ",").split(",") if x.strip().isdigit()}

    def allowed_usernames(self) -> set[str]:
        raw = self.telegram_allowed_usernames.replace(";", ",")
        return {x.strip().lstrip("@").lower() for x in raw.split(",") if x.strip()}

    def _id_set(self, raw: str) -> set[int]:
        return {int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()}

    def _name_set(self, raw: str) -> set[str]:
        return {x.strip().lstrip("@").lower() for x in raw.replace(";", ",").split(",") if x.strip()}

    @property
    def owner_ids(self) -> set[int]:
        return self._id_set(self.telegram_owner_ids) or self.allowed_ids()

    @property
    def owner_usernames(self) -> set[str]:
        return self._name_set(self.telegram_owner_usernames) or self.allowed_usernames()

    @property
    def task_creator_ids(self) -> set[int]:
        own = self._id_set(self.telegram_task_creator_ids)
        return own or self.owner_ids

    @property
    def task_creator_usernames(self) -> set[str]:
        own = self._name_set(self.telegram_task_creator_usernames)
        return own or self.owner_usernames

    @property
    def app_dir(self) -> str:
        """ریشهٔ پروژه (برای فایل‌های دادهٔ محلی)."""
        import pathlib

        return str(pathlib.Path(__file__).resolve().parent.parent)

    @property
    def active_llm_key(self) -> str:
        """کلید متناسب با LLM_PROVIDER."""
        return {
            "offline": "",         # هیچ کلیدی لازم نیست
            "groq": self.groq_api_key,
            "gemini": self.gemini_api_key,
            "openrouter": self.openrouter_api_key,
            "deepseek": self.deepseek_api_key,
            "ollama": "",          # کلید لازم ندارد
            "custom": self.openai_api_key,
        }.get((self.llm_provider or "openai").lower(), self.openai_api_key)

    @property
    def webhook_url(self) -> str:
        return f"{self.public_base_url.rstrip('/')}{self.webhook_path}"

    @property
    def task_command_list(self) -> tuple[str, ...]:
        """پیشوندهای دستور وظیفه از .env."""
        raw = self.task_command_aliases or "task"
        items = tuple(
            x.strip() for x in re.split(r"[,;]", raw) if x.strip()
        )
        return items or ("task", "ta", "assign", "وظیفه", "کار")

    def human_ids(self, code: str) -> set[int]:
        """شناسه‌های تلگرام یک انسان (H01..H03)."""
        return self._id_set(getattr(self, f"human_{code.lower()}_ids", "") or "")

    def human_usernames(self, code: str) -> set[str]:
        return self._name_set(getattr(self, f"human_{code.lower()}_usernames", "") or "")

    @property
    def source_dbs(self) -> dict[str, str]:
        """نگاشت نام منطقی → شناسهٔ دیتابیس منابع موجود."""
        return {
            "tasks": self.notion_db_tasks or self.notion_tasks_db,
            "roles": self.notion_db_roles,
            "revenue": self.notion_db_revenue,
        }

    @property
    def sheets_internal_url(self) -> str:
        return f"http://127.0.0.1:{self.port}/internal/sheets/push"

    def notion_db_id(self, agent_id: str) -> str:
        """شناسه دیتابیس Notion مربوط به یک ایجنت."""
        field = NOTION_DB_FIELDS.get(agent_id.upper())
        return getattr(self, field, "") if field else ""

    @property
    def notion_db_map(self) -> dict[str, str]:
        return {agent: self.notion_db_id(agent) for agent in NOTION_DB_FIELDS}

    def task_status(self, role: str) -> str:
        """نام واقعی یک وضعیت وظیفه: role ∈ todo|doing|review|done|blocked|rejected|backlog."""
        return {
            "todo": self.notion_task_status_todo,
            "doing": self.notion_task_status_doing,
            "review": self.notion_task_status_review,
            "done": self.notion_task_status_done,
            "blocked": self.notion_task_status_blocked,
            "rejected": self.notion_task_status_rejected,
            "backlog": self.notion_task_status_backlog,
        }.get(role, role)

    @property
    def notion_task_props(self) -> dict[str, str]:
        """نگاشت نقش → نام پراپرتی واقعی دیتابیس Tasks."""
        return {
            "title": self.notion_task_title_prop,
            "assignee": self.notion_task_assignee_prop,
            "status": self.notion_task_status_prop,
            "priority": self.notion_task_priority_prop,
            "description": self.notion_task_description_prop,
            "result": self.notion_task_result_prop,
            "evidence": self.notion_task_evidence_prop,
            "parent": self.notion_task_parent_prop,
            "source": self.notion_task_source_prop,
            "chat_id": self.notion_task_chatid_prop,
            "requester": self.notion_task_requester_prop,
            "trace": self.notion_task_trace_prop,
            "created": self.notion_task_created_prop,
            "topic": self.notion_task_topic_prop,
            "link": self.notion_task_link_prop,
        }


@lru_cache(maxsize=1)
def get_settings() -> Settings:
    return Settings()


settings = get_settings()


# --------------------------------------------------------------------------- #
#  اعمال تنظیمات واردشده از ویزارد تلگرام (روی همان آبجکت سراسری settings)
# --------------------------------------------------------------------------- #
INT_FIELDS = {"port", "notion_records_limit", "history_limit", "openai_max_tokens", "max_reply_chars"}
FLOAT_FIELDS = {"openai_temperature", "agent_delay_seconds", "openai_timeout"}
BOOL_FIELDS = {"drop_pending_updates", "allowed_users_strict", "setup_wizard_enabled"}


def field_for_key(key: str) -> str | None:
    """نام ENV/ویزارد (مثل NOTION_DB_MARKET) → نام فیلد پایتونی."""
    name = key.strip().upper()
    field = name.lower()
    return field if field in Settings.model_fields else None


def apply_overrides(overrides: dict[str, str]) -> list[str]:
    """اعمال اجباری تنظیمات ذخیره‌شده (اولویت بر .env). فهرست کلیدهای اعمال‌شده را برمی‌گرداند."""
    applied: list[str] = []
    for key, value in (overrides or {}).items():
        field = field_for_key(key)
        if field is None:
            continue
        try:
            if field in INT_FIELDS:
                coerced: object = int(value)
            elif field in FLOAT_FIELDS:
                coerced = float(value)
            elif field in BOOL_FIELDS:
                coerced = str(value).strip().lower() in {"1", "true", "yes", "on"}
            else:
                coerced = str(value)
            setattr(settings, field, coerced)
            applied.append(field)
        except (TypeError, ValueError):
            continue
    return applied


CONFIG_KEYS: tuple[str, ...] = (
    "TELEGRAM_BOT_TOKEN",
    "OPENAI_API_KEY",
    "NOTION_API_KEY",
    "NOTION_DAILY_LOG_DB",
    "MONGODB_URI",
    "TELEGRAM_ALLOWED_USER_IDS",
    "TELEGRAM_ALLOWED_USERNAMES",
    "NOTION_DB_MARKET",
    "NOTION_DB_COPY",
    "NOTION_DB_CONTENT",
    "NOTION_DB_DESIGN",
    "NOTION_DB_WEB",
    "NOTION_DB_SEO",
    "NOTION_DB_DATA",
    "NOTION_DB_CAMPAIGN",
)

SECRET_KEYS: frozenset[str] = frozenset({"TELEGRAM_BOT_TOKEN", "OPENAI_API_KEY", "NOTION_API_KEY"})
