"""
Per-group "buy" referral link.

Whoever adds the bot to a group (if they're an admin of that group) can
register their own referral link; the "خرید ..." button under price/amount
replies sent in that group then points to it instead of the global default
(config.BUY_COIN_URL).

Backed by a small JSON file (same pattern as core/state.py used to be)
rather than an in-process dict, so it survives across Passenger/Flask worker
processes.
"""

import json
import os
import threading

from .. import config

_lock = threading.Lock()
_TABLE = "group_links"


def _path() -> str:
    return os.path.join(config.DATA_DIR, f"{_TABLE}.json")


def _load() -> dict:
    path = _path()
    if not os.path.exists(path):
        return {}
    with open(path, "r", encoding="utf-8") as fh:
        try:
            return json.load(fh)
        except json.JSONDecodeError:
            return {}


def _save(data: dict) -> None:
    os.makedirs(config.DATA_DIR, exist_ok=True)
    with open(_path(), "w", encoding="utf-8") as fh:
        json.dump(data, fh, ensure_ascii=False, indent=2)


def get_link(chat_id):
    """Registered referral link for this chat, or None if none was set."""
    if chat_id is None:
        return None
    with _lock:
        return _load().get(str(chat_id))


def set_link(chat_id, url: str) -> None:
    with _lock:
        data = _load()
        data[str(chat_id)] = url
        _save(data)
