"""
ابزار ویرایش امن فایل .env (بدون وابستگی به ادیتور و بدون مشکل BOM/CRLF/کلید تکراری).

استفاده:
    python tools/env_tool.py show
    python tools/env_tool.py set OPENAI_API_KEY sk-xxx NOTION_API_KEY ntn_xxx
    python tools/env_tool.py fix [TOKEN]
    python tools/env_tool.py list
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

APP_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(APP_DIR))


def env_path() -> Path:
    return Path(os.getenv("ENV_FILE") or (APP_DIR / ".env"))


def mask(key: str, value: str) -> str:
    if not value:
        return "(خالی)"
    upper = key.upper()
    if any(h in upper for h in ("TOKEN", "KEY", "SECRET", "URI")):
        return value if upper in {"MONGODB_URI", "PUBLIC_BASE_URL"} else (
            value[:6] + "…" + value[-4:] if len(value) > 12 else "••••"
        )
    return value


def load() -> tuple[Path, list[str], dict[str, str], list[str]]:
    """(مسیر، ترتیب کلیدها، مقادیر، خطوط سرآیند/کامنت)"""
    base = env_path()
    header: list[str] = []
    if not base.exists():
        example = APP_DIR / ".env.example"
        base.write_text(example.read_text(encoding="utf-8") if example.exists() else "", encoding="utf-8")
        print("  .env از .env.example ساخته شد")

    raw = base.read_bytes()
    if raw.startswith(b"\xef\xbb\xbf"):
        raw = raw[3:]
        print("  BOM حذف شد")
    text = raw.decode("utf-8", errors="replace")

    order: list[str] = []
    values: dict[str, str] = {}
    for line in text.splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#") or "=" not in stripped:
            if stripped.startswith("#") and not order:
                header.append(line)
            continue
        if stripped.startswith("export "):
            stripped = stripped[len("export "):].strip()
        key, value = stripped.split("=", 1)
        key, value = key.strip(), value.strip()
        if key in values and values[key] != value:
            print(f"  کلید تکراری «{key}» → آخرین مقدار نگه داشته شد")
        if key not in values:
            order.append(key)
        values[key] = value
    return base, order, values, header


def save(base: Path, order: list[str], values: dict[str, str], header: list[str]) -> None:
    body = [f"{key}={values[key]}" for key in order]
    base.write_text("\n".join(header + body) + "\n", encoding="utf-8")
    try:
        os.chmod(base, 0o600)
    except OSError:
        pass


def valid_keys() -> set[str]:
    from config.settings import Settings

    return {name.upper() for name in Settings.model_fields}


def cmd_show() -> int:
    from config.settings import settings

    base = env_path()
    print(f"فایل .env خوانده‌شده: {base}  (موجود: {base.exists()})")
    print(f"ENV_FILE: {os.getenv('ENV_FILE') or '(تنظیم نشده)'}")
    print("")
    for key in (
        "TELEGRAM_BOT_TOKEN",
        "OPENAI_API_KEY",
        "NOTION_API_KEY",
        "NOTION_DAILY_LOG_DB",
        "MONGODB_URI",
        "PUBLIC_BASE_URL",
        "TELEGRAM_ALLOWED_USER_IDS",
        "TELEGRAM_ALLOWED_USERNAMES",
        "ALLOWED_USERS_STRICT",
        "SETUP_WIZARD_ENABLED",
    ):
        value = getattr(settings, key.lower(), "") or ""
        print(f"  {key:<26} = {mask(key, str(value))}")
    print("")
    print("  دیتابیس‌های ایجنت‌ها:")
    for agent in ("AG01", "AG02", "AG03", "AG04", "AG05", "AG06", "AG07", "AG08"):
        db_id = settings.notion_db_id(agent)
        print(f"    {agent} → {db_id or '(خالی)'}")
    token = settings.telegram_bot_token or ""
    if not token:
        print("\n  ⚠️ توکن خالی است: ./run.sh token <TOKEN>")
    return 0


def cmd_list() -> int:
    for key in sorted(valid_keys()):
        print("  " + key)
    return 0


def cmd_set(pairs: list[str]) -> int:
    if not pairs or len(pairs) % 2 != 0:
        print("  خطا: کلید و مقدار باید جفت باشند.  مثال: ./run.sh set OPENAI_API_KEY sk-...")
        return 1

    base, order, values, header = load()
    allowed = valid_keys()
    changed = 0
    for index in range(0, len(pairs), 2):
        key, value = pairs[index].strip().upper(), pairs[index + 1].strip()
        if key not in allowed:
            print(f"  ✗ کلید ناشناخته: {key} — فهرست: ./run.sh set --list")
            continue
        if key not in values:
            order.append(key)
        values[key] = value
        changed += 1
        print(f"  ✓ {key} = {mask(key, value)}")

    if changed:
        save(base, order, values, header)
        print(f"  ذخیره شد در: {base}  ({changed} کلید)")
        print("  اعمال تغییرات:  ./run.sh restart")
    else:
        print("  هیچ کلیدی تغییر نکرد.")
        return 1
    return 0


def cmd_fix(token: str = "") -> int:
    base, order, values, header = load()

    if token:
        parts = token.split(":", 1)
        if len(parts) == 2 and parts[0].isdigit() and len(token) > 30:
            if "TELEGRAM_BOT_TOKEN" not in values:
                order.append("TELEGRAM_BOT_TOKEN")
            values["TELEGRAM_BOT_TOKEN"] = token
            print("  TELEGRAM_BOT_TOKEN ثبت شد")
        else:
            print("  توکن داده‌شده قالب معتبری ندارد و نوشته نشد")

    save(base, order, values, header)
    current = values.get("TELEGRAM_BOT_TOKEN", "")
    print(f"  توکن در فایل: {mask('TOKEN', current)}")
    print(f"  تعداد کلیدها: {len(order)}")
    print(f"  مسیر: {base}  (دسترسی 600)")
    return 0


def main(argv: list[str]) -> int:
    command = argv[1] if len(argv) > 1 else "show"
    if command == "show":
        return cmd_show()
    if command == "list":
        return cmd_list()
    if command == "set":
        return cmd_set(argv[2:])
    if command == "fix":
        return cmd_fix(argv[2] if len(argv) > 2 else "")
    print(__doc__)
    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
