# -*- coding: utf-8 -*-
import sys, os, glob, datetime
sys.stdout.reconfigure(encoding='utf-8')
import openpyxl

BASE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '광역_사이트맵')
TODAY = datetime.date(2026, 6, 2)
YDAY = datetime.date(2026, 6, 1)

def freelancer(prov):
    if any(k in prov for k in ('충청남도', '충청북도')):
        return '프리랜서1 (충남·충북)'
    if any(k in prov for k in ('전북', '제주')):
        return '프리랜서2 (전북·제주)'
    return '기타/' + prov

def datarows(path):
    try:
        wb = openpyxl.load_workbook(path, read_only=True)
        ws = wb.active
        n = 0
        for row in ws.iter_rows(min_row=3, min_col=2, max_col=2):
            if row[0].value not in (None, ''):
                n += 1
        wb.close()
        return n
    except Exception as e:
        return 'ERR:' + str(e)

rows = []
for p in glob.glob(os.path.join(BASE, '*', '*', '*.xlsx')):
    bn = os.path.basename(p)
    if bn.startswith('_') or 'backup' in p or '_r2' in p or 'backup' in bn:
        continue
    d = datetime.date.fromtimestamp(os.path.getmtime(p))
    if d not in (TODAY, YDAY):
        continue
    parts = p.replace(BASE + os.sep, '').split(os.sep)
    prov = parts[0]
    inst = bn.replace('.xlsx', '')
    rows.append((d, prov, inst, freelancer(prov), datarows(p), os.path.getmtime(p)))

rows.sort(key=lambda x: (x[0], x[3], x[5]))

for label, day in [('어제 (2026-06-01)', YDAY), ('오늘 (2026-06-02)', TODAY)]:
    drows = [r for r in rows if r[0] == day]
    print(f'\n===== {label} — 수정 파일 {len(drows)}개 =====')
    for d, prov, inst, fl, n, mt in drows:
        ts = datetime.datetime.fromtimestamp(mt).strftime('%H:%M')
        print(f'  [{fl[:5]}] {prov} / {inst}: {n}행  (수정 {ts})')

print('\n===== 프리랜서별 통계 =====')
for label, day in [('어제 (2026-06-01)', YDAY), ('오늘 (2026-06-02)', TODAY)]:
    drows = [r for r in rows if r[0] == day]
    print(f'\n[{label}]')
    byfl = {}
    for d, prov, inst, fl, n, mt in drows:
        byfl.setdefault(fl, []).append((inst, n))
    for fl in sorted(byfl):
        items = byfl[fl]
        tot = sum(n for _, n in items if isinstance(n, int))
        print(f'  {fl}: {len(items)}개 파일, 합계 {tot}행')
        for inst, n in items:
            print(f'      - {inst}: {n}행')

# 양일 합산
print('\n[어제+오늘 합산]')
byfl = {}
for d, prov, inst, fl, n, mt in rows:
    byfl.setdefault(fl, set())
for d, prov, inst, fl, n, mt in rows:
    byfl[fl].add(inst)
for fl in sorted(byfl):
    print(f'  {fl}: {len(byfl[fl])}개 기관(중복제거)')
