# Dong bo quyen kenh VipTrend tu website xuong may key (28/09/2026).
#
# Khac moi backend khac: key signal la MOT HASH MOI KEY - keysign:{license}, moi truong la mot
# kenh (GOLDVIP4...) mang JSON {expired, username, owner, mt5_id, account, active_clients, tg_id,
# created_by}. May key doc o routes/signal.py (/signal_license) - EA VipTrend va tab VIPTREND cua
# MT5 Manager. Chu du an: "moi khach duoc cap 1 key signal chung, va cap quyen vao tung signal".
#
# Website: moi con VIP la mot san pham, license_backend = 'sig:<kenh>'; /api/keys tra cac don CON
# HAN (key_active = key chung cua khach, backend = sig:<kenh>, expired = ngay).
#
# AN TOAN - key cap tay bang quangkey van song song (chu du an: "khach cap tay de nguyen"):
#   - CHI sua / xoa truong co created_by = "web" (truong do chinh bo nay tao ra);
#   - key + kenh da co ban ghi tay -> bo qua, khong ghi de;
#   - giu mt5_id / account / active_clients ma EA da ghi (chi doi expired, username);
#   - API tra rong ma may key dang co nhieu truong web -> KHONG xoa (nghi loi API), ghi log.
import json
import logging

try:
    from .redis_client import get_redis_connection
except ImportError:
    from redis_client import get_redis_connection

logger = logging.getLogger(__name__)

SIG_DB = 4                      # may key: config.ini [redis_signal] dbsignal = 4
TIEN_TO = 'keysign:'
NGUON = 'web'


def la_backend_sig(backend):
    return isinstance(backend, str) and backend.startswith('sig:') and len(backend) > 4


def dong_bo(items):
    """items: danh sach tu /api/keys (key_active, expired 'Y-m-d', username, backend 'sig:<kenh>')."""
    muon = {}
    for it in items:
        lic, be, het = str(it.get('key_active') or ''), str(it.get('backend') or ''), str(it.get('expired') or '')
        if not lic or not la_backend_sig(be) or len(het) != 10:
            continue
        muon[(lic, be[4:])] = {'expired': het, 'username': str(it.get('username') or '')}

    r = get_redis_connection(SIG_DB)
    co = {}                                      # (lic, kenh) -> info, chi truong do web tao
    for khoa in r.scan_iter(match=TIEN_TO + '*', count=500):
        lic = khoa[len(TIEN_TO):]
        for kenh, gt in r.hgetall(khoa).items():
            try:
                info = json.loads(gt)
            except (TypeError, ValueError):
                continue
            if info.get('created_by') == NGUON:
                co[(lic, kenh)] = info

    if not muon and len(co) > 3:
        logger.error("[keysign] API tra 0 don VipTrend con han nhung may key co %d quyen web — "
                     "nghi loi API, KHONG xoa", len(co))
        return

    them = sua = bo_qua = 0
    for (lic, kenh), m in muon.items():
        cu = co.get((lic, kenh))
        if cu is None:
            hien = r.hget(TIEN_TO + lic, kenh)
            if hien is not None:
                bo_qua += 1                      # da co ban ghi tay cho key + kenh nay - khong dung
                continue
            r.hset(TIEN_TO + lic, kenh, json.dumps({
                'expired': m['expired'], 'username': m['username'], 'owner': m['username'],
                'mt5_id': '', 'account': '', 'active_clients': '', 'tg_id': '', 'created_by': NGUON}))
            them += 1
        elif cu.get('expired') != m['expired'] or cu.get('username') != m['username']:
            cu.update(m)
            cu['owner'] = m['username']
            r.hset(TIEN_TO + lic, kenh, json.dumps(cu))
            sua += 1

    xoa = 0
    for (lic, kenh), info in co.items():
        if (lic, kenh) in muon:
            continue
        r.hdel(TIEN_TO + lic, kenh)
        mt5 = info.get('mt5_id')
        # Bo chi muc webhook cua may key neu no con tro vao dung ban ghi nay
        if mt5 and r.hget('sigidx:' + kenh, mt5) == TIEN_TO + lic + '|' + kenh:
            r.hdel('sigidx:' + kenh, mt5)
        xoa += 1

    if them or sua or xoa or bo_qua:
        logger.info("[keysign] them %d, sua %d, xoa %d (het han / huy), bo qua %d (da co ban cap tay)",
                    them, sua, xoa, bo_qua)
