#!/usr/bin/env python3
"""Verification helper: snapshot counts of the 4 MCP files + shipment/workbench files."""
import json, os, sys, collections

D = os.path.dirname(os.path.abspath(__file__))
OUT = sys.argv[1] if len(sys.argv) > 1 else '/tmp/refresh_baseline.json'
snap = {}

def mtime(p):
    try:
        import datetime
        return datetime.datetime.fromtimestamp(os.stat(p).st_mtime).strftime('%Y-%m-%d %H:%M:%S')
    except Exception:
        return None

# complaints
p = os.path.join(D, 'mcp_complaints.json')
try:
    d = json.load(open(p))
    items = d.get('items', [])
    snap['complaints'] = {
        'total': len(items), 'declared': d.get('total'), 'updated': d.get('updated'),
        'mtime': mtime(p),
        'creators': dict(collections.Counter(i.get('creator', '') for i in items)),
        'transitional': {k: sum(1 for i in items if i.get('creator') == k) for k in ('黄明月', '张立娅', '刘子研')},
    }
except Exception as e:
    snap['complaints'] = {'error': str(e)}

# customers
p = os.path.join(D, 'mcp_customers.json')
try:
    d = json.load(open(p))
    cs = d.get('customers', [])
    snap['customers'] = {'total': len(cs), 'updated_at': d.get('updated_at'), 'mtime': mtime(p)}
except Exception as e:
    snap['customers'] = {'error': str(e)}

# activities
p = os.path.join(D, 'daily_activities_mcp.json')
try:
    d = json.load(open(p))
    its = d.get('items', [])
    months = collections.Counter((i.get('start_time') or '')[:7] for i in its)
    owners = collections.Counter((i.get('owner') or {}).get('name_cn', '') for i in its)
    snap['activities'] = {
        'total': len(its), 'declared': d.get('total'), 'updated': d.get('updated'), 'mtime': mtime(p),
        'months': dict(sorted(months.items())),
        'first_date': min((i.get('start_time') or '9999') for i in its) if its else None,
        'top_owners': dict(owners.most_common(5)),
    }
except Exception as e:
    snap['activities'] = {'error': str(e)}

# orders
p = os.path.join(D, 'mcp_orders_input.json')
try:
    d = json.load(open(p))
    tns = {(o.get('物流单号') or '').strip() for o in d if (o.get('物流单号') or '').strip()}
    fo = [o for o in d if str(o.get('单据编号') or '').startswith('FO')]
    snap['orders'] = {
        'total': len(d), 'unique_tracking': len(tns), 'fo_count': len(fo), 'mtime': mtime(p),
        'sample_nos': sorted({str(o.get('单据编号') or '') for o in d})[:3],
    }
except Exception as e:
    snap['orders'] = {'error': str(e)}

for f in ('shipment_status.json', 'workbench_data.json', 'my_activities.json', 'kpi_progress.json'):
    fp = os.path.join(D, f)
    snap[f] = {'exists': os.path.exists(fp), 'mtime': mtime(fp), 'size': os.path.getsize(fp) if os.path.exists(fp) else None}

json.dump(snap, open(OUT, 'w'), ensure_ascii=False, indent=1)
print(json.dumps(snap, ensure_ascii=False, indent=1))
