"""Создать 5 групп (папок) в TickTick и засунуть в них наши 15 проектов.

Запуск:
    .venv/bin/python -m scripts.setup_ticktick_groups

1. Читает scripts/preflight/projects_mapping.json — наши 15 projectId
2. Для каждой из 5 «брендов» (Mars/Channel/Consulting/Life/Vibe Coding):
   - смотрит существующие папки в TickTick;
   - если имя свободно — создаёт `<Brand>`;
   - если занято — создаёт `<Brand> (new)` (Наташа потом переименует);
3. Обновляет каждый из 15 наших проектов: ставит groupId через
   POST /project/{id}.
4. Сохраняет расширенный маппинг в scripts/preflight/projects_mapping.json
   (имя → {id, groupId}).
"""
import json
from pathlib import Path

from scripts.preflight import config
from scripts.preflight import http_client as http

BRANDS = ["Mars", "Channel", "Consulting", "Life", "Vibe Coding"]

# Для group create — кажется TickTick требует sortOrder, попробуем без; если
# падает — добавим.
DEFAULT_GROUP_PAYLOAD: dict = {}


def _which_brand(project_name: str) -> str | None:
    """`Mars - To Do` → `Mars`."""
    for brand in BRANDS:
        if project_name.startswith(brand + " - "):
            return brand
    return None


def main() -> None:
    cfg = config.load()
    token = cfg.access_token
    assert token, "no token"

    mapping_path = Path("scripts/preflight/projects_mapping.json")
    mapping: dict[str, str] = json.loads(mapping_path.read_text(encoding="utf-8"))
    print(f"Загружено проектов из mapping: {len(mapping)}")

    # 1. Список существующих папок
    existing_groups = http.get("project/group", token) or []
    existing_names = {g["name"]: g["id"] for g in existing_groups}
    print(f"Существующих папок: {len(existing_groups)}")

    # 2. Создать наши папки
    brand_to_group_id: dict[str, str] = {}
    for brand in BRANDS:
        wanted_name = brand
        if wanted_name in existing_names:
            wanted_name = f"{brand} (new)"
        if wanted_name in existing_names:
            # Если и (new) занято — берём существующий
            brand_to_group_id[brand] = existing_names[wanted_name]
            print(f"  ⊙ reuse  {wanted_name:<25} → {existing_names[wanted_name]}")
            continue
        result = http.post("project/group", token, {"name": wanted_name})
        gid = result["id"]
        brand_to_group_id[brand] = gid
        print(f"  + create {wanted_name:<25} → {gid}")

    # 3. Привязать наши 15 проектов к папкам через POST /project/{id}
    updated_mapping: dict[str, dict] = {}
    for project_name, project_id in mapping.items():
        brand = _which_brand(project_name)
        if not brand:
            print(f"  ! skip (no brand match): {project_name}")
            updated_mapping[project_name] = {"id": project_id, "groupId": None}
            continue
        gid = brand_to_group_id[brand]
        # POST /project/{id} с groupId — нужны обязательные поля (name, color)
        # Сначала прочитаем текущий проект
        current = http.get(f"project/{project_id}", token)
        payload = {
            "id": project_id,
            "name": current["name"],
            "color": current.get("color"),
            "groupId": gid,
        }
        http.post(f"project/{project_id}", token, payload)
        print(f"  → {project_name:<28} → group {brand}")
        updated_mapping[project_name] = {"id": project_id, "groupId": gid}

    # 4. Перезаписать mapping расширенно
    mapping_path.write_text(
        json.dumps(updated_mapping, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    print(f"\nОбновлённый mapping: {mapping_path}")


if __name__ == "__main__":
    main()
