# -*- coding: utf-8 -*-
"""검수완료·미제출 통계 (날짜별·프리랜서별). 읽기전용.
사용: python _통계.py
대상: 작업현황.xlsx (검수=완료 AND 제출완료!=완료)
"""
import sys, os
from collections import defaultdict
import openpyxl

sys.stdout.reconfigure(encoding="utf-8")
BASE = os.path.dirname(os.path.abspath(__file__))
# 광역 작업현황.xlsx는 정리(삭제)됨 → 공공기관2 현황판 기준(2026-06-18)
XLSX = os.path.join(BASE, "공공기관2", "공공기관2_작업현황.xlsx")

wb = openpyxl.load_workbook(XLSX, data_only=True)
ws = wb["현황"] if "현황" in wb.sheetnames else wb.active
hdr = [c.value for c in ws[1]]
gi = lambda n: hdr.index(n)

rows = []
for r in ws.iter_rows(min_row=2, values_only=True):
    if not r[gi("기관")]:
        continue
    if r[gi("검수")] == "완료" and r[gi("제출완료")] != "완료":
        rows.append((str(r[gi("검수완료일")] or "")[:10], r[gi("담당자")], r[gi("기관")], r[gi("행수")] or 0))
rows.sort(key=lambda x: (x[0], x[1]))

# 프리랜서 라벨 정규화(충남/충북=프1, 전북/제주=프2 표기 보조)
dates = sorted({d for d, *_ in rows})
frees = ["프리랜서1", "프리랜서2"]

bydate = defaultdict(lambda: defaultdict(list))
byfree = defaultdict(lambda: [0, 0])
for d, f, name, n in rows:
    bydate[d][f].append((name, n))
    byfree[f][0] += 1
    byfree[f][1] += n

def cell(items):
    return ", ".join(f"{nm} {n}" for nm, n in items) if items else "—"

print("## 검수완료 · 미제출 통계\n")
print("### 📅 날짜별 · 프리랜서별\n")
print("| 검수일 | 프리랜서1 (충남) | 프리랜서2 (전북) | 일계 |")
print("|---|---|---|---|")
tot_cnt = tot_row = 0
for d in dates:
    c1 = bydate[d].get("프리랜서1", [])
    c2 = bydate[d].get("프리랜서2", [])
    day_cnt = len(c1) + len(c2)
    day_row = sum(n for _, n in c1) + sum(n for _, n in c2)
    tot_cnt += day_cnt
    tot_row += day_row
    print(f"| {d} | {cell(c1)} | {cell(c2)} | {day_cnt}곳 · {day_row:,}행 |")
s1 = byfree.get("프리랜서1", [0, 0])
s2 = byfree.get("프리랜서2", [0, 0])
print(f"| **소계** | **{s1[0]}곳 · {s1[1]:,}행** | **{s2[0]}곳 · {s2[1]:,}행** | **{tot_cnt}곳 · {tot_row:,}행** |")

print("\n### 👤 프리랜서별 요약\n")
print("| 프리랜서 | 기관 | 행수 |")
print("|---|---|---|")
for f in frees:
    items = [(nm, n) for d in dates for nm, n in bydate[d].get(f, [])]
    names = ", ".join(f"{nm}({n})" for nm, n in items) if items else "—"
    print(f"| {f} | {names} | **{byfree.get(f,[0,0])[1]:,}** |")
print(f"| **합계** | **{tot_cnt}곳** | **{tot_row:,}** |")
