# -*- coding: utf-8 -*-
"""SINH_MAP.PY — dung lai module_map.json TU MA NGUON, chay lai duoc.

VI SAO CAN TEP NAY
------------------
module_map.json ban cu chep tay, va da lech: no khai `include/core` phang 22
tep trong khi ma da tach thanh ba thu muc con (core/orders, core/tp_sl,
core/grid), va khong khai `include/dll`. Tai lieu viet tay luon tut lai sau
ma — cach duy nhat het lech la SINH RA no.

Chay:  python sinh_map.py <thu_muc_ea> <tep_ra.json>
"""
import io, json, os, re, sys
from datetime import date

GOC = sys.argv[1] if len(sys.argv) > 1 else r'G:/server tin hieu/systemai/dca/ea'
RA = sys.argv[2] if len(sys.argv) > 2 else 'module_map_moi.json'


def doc(p):
    for bm in ('utf-8', 'utf-8-sig', 'cp1258', 'latin-1'):
        try:
            return io.open(p, encoding=bm).read()
        except (UnicodeDecodeError, LookupError):
            continue
    return ''


def mo_ta(s, ten_tep):
    """Mo ta that o dau tep, bo khung ke va dong lap ten tep."""
    goc_ten = ten_tep.replace('.mqh', '').replace('.mq5', '').lower()
    lay = []
    for d in s.splitlines()[:45]:
        t = d.strip()
        if not t.startswith('//') and not t.startswith('/*'):
            if lay:
                break
            continue
        noi = t.lstrip('/*').strip().strip('|').strip().strip('+-= ').strip()
        if not noi:
            continue
        thap = noi.lower()
        if goc_ten in thap and len(noi) < 40:
            continue
        if any(x in thap for x in ('copyright', 'http://', 'https://',
                                   'property ', 'all rights')):
            continue
        lay.append(noi)
        if len(lay) >= 3:
            break
    return ' · '.join(lay)[:280]


# ---- quet cay that ---------------------------------------------------
cay, tong, tong_dong, tong_input = {}, 0, 0, 0
for thu, _, teps in os.walk(os.path.join(GOC, 'include')):
    ds = sorted(t for t in teps if t.endswith('.mqh'))
    if not ds:
        continue
    nhom = os.path.relpath(thu, GOC).replace(os.sep, '/')
    muc = []
    for t in ds:
        s = doc(os.path.join(thu, t))
        so_dong = len(s.splitlines())
        so_input = len(re.findall(r'^\s*(?:input|sinput)\s', s, re.M))
        muc.append({'tep': t, 'dong': so_dong, 'input': so_input,
                    'mo_ta': mo_ta(s, t)})
        tong += 1
        tong_dong += so_dong
        tong_input += so_input
    cay[nhom] = muc

# ---- filter: gom theo ho, doc tu chinh ten tep -----------------------
HO_FILTER = {
    'dao_dong': ('Stoch', 'RSI', 'CCI', 'WilliamsR', 'MFI', 'DeMarker',
                 'UltimateOsc', 'RCI', 'RVI'),
    'xu_huong': ('ADX', 'DMI', 'Aroon', 'Choppiness', 'MACDHist',
                 'ParabolicSAR', 'Supertrend', 'ElderPower', 'VIDYA', 'Ichimoku'),
    'bien_dong': ('ATR', 'BollingerB', 'ADR', 'Squeeze'),
    'kenh_gia': ('BBChannel', 'KeltnerChannel', 'DonchianChannel'),
    'khac': ('OBV', 'Pivot', 'RangePosition'),
}
ten_filter = [m['tep'][len('DCA_Filter_'):-len('.mqh')]
              for m in cay.get('include/filters', [])
              if m['tep'].startswith('DCA_Filter_')]
da_xep = {x for ds in HO_FILTER.values() for x in ds}
chua_xep = sorted(set(ten_filter) - da_xep)

# ---- thu muc khong co .mqh (vd dll) ---------------------------------
khac = {}
for thu, _, teps in os.walk(os.path.join(GOC, 'include')):
    if any(t.endswith('.mqh') for t in teps) or not teps:
        continue
    khac[os.path.relpath(thu, GOC).replace(os.sep, '/')] = sorted(teps)

ket = {
    '_sinh_boi': 'sinh_map.py — CHAY LAI DUOC, dung chep tay',
    '_sinh_ngay': date.today().isoformat(),
    '_canh_bao': ('Tep nay SINH TU MA NGUON. Dung sua tay — sua xong lan '
                  'sinh sau se de len. Muon doi mo ta thi sua chu thich o '
                  'dau tep .mqh tuong ung.'),
    'du_an': 'SMART DCA EA',
    'phien_ban_hien_thi': '11.9',
    'phien_ban_ma_nguon': 'dcav119',
    'tep_chinh': 'dcav119.mq5',
    'tong_module': tong,
    'tong_dong': tong_dong,
    'tong_input': tong_input,
    'cay_thu_muc': cay,
    'thu_muc_khong_co_mqh': khac,
    'ho_filter': {k: list(v) for k, v in HO_FILTER.items()},
    'filter_chua_xep_ho': chua_xep,
    'che_do_hanh_dong_filter': [
        'CLOSE_BLOCK — dong lenh + chan ca hai chieu',
        'BLOCK_ONLY — chi chan mot chieu, khong dong',
        'CONTINUE_BLOCK — chay tiep + chan hai chieu',
        'CLOSE_BOTH — dong ca hai chuoi + chan mot chieu',
        'SMART_RESET — dong roi mo lai',
        'BREAKEVEN — chan mot chieu + keo TP ve bo',
        'SWITCH_MECH — doi sang co che Market Stop',
        'ESCALATION — leo thang theo so filter cung bao',
    ],
    'khong_dua_vao_gioi_thieu': {
        'DCA_EarlyCut.mqh': ('Phan thu nghiem rieng, ban phat hanh se khong '
                             'co. Chu du an dan KHONG de cap trong gioi thieu.'),
    },
}

io.open(RA, 'w', encoding='utf-8', newline='\n').write(
    json.dumps(ket, ensure_ascii=False, indent=1))

print('SINH XONG -> %s' % RA)
print('  %d module · %s dong · %d input' % (tong, format(tong_dong, ','), tong_input))
for nhom in sorted(cay):
    print('  %-24s %2d tep' % (nhom, len(cay[nhom])))
if khac:
    print('  thu muc khong co .mqh:', ', '.join(khac))
if chua_xep:
    print('  CANH BAO filter chua xep ho:', ', '.join(chua_xep))
