#!/usr/bin/env python3
"""V2.0 per-device revenue from launch to 2026-05-31"""
import subprocess, json, urllib.parse, time, sys

months = [
    ("2025-11", "2025-11-01 00:00:00", "2025-11-30 23:59:59"),
    ("2025-12", "2025-12-01 00:00:00", "2025-12-31 23:59:59"),
    ("2026-01", "2026-01-01 00:00:00", "2026-01-31 23:59:59"),
    ("2026-02", "2026-02-01 00:00:00", "2026-02-28 23:59:59"),
    ("2026-03", "2026-03-01 00:00:00", "2026-03-31 23:59:59"),
    ("2026-04", "2026-04-01 00:00:00", "2026-04-30 23:59:59"),
    ("2026-05", "2026-05-01 00:00:00", "2026-05-31 23:59:59"),
]

all_orders = []

for label, st, et in months:
    url = (f'https://new.baiguoyu888.tech/api/order/list?page=1&size=10000'
           f'&startTime={urllib.parse.quote(st)}&endTime={urllib.parse.quote(et)}')
    print(f'Fetching {label}...', end=' ', flush=True)
    t0 = time.time()
    r = subprocess.run(
        ['curl', '-s', '-b', '/tmp/v2_cookies.txt', '-H', 'client-type: admin', url],
        capture_output=True, text=True, timeout=180
    )
    elapsed = time.time() - t0
    try:
        data = json.loads(r.stdout)
        records = data.get('data', {}).get('records', [])
        total = data.get('data', {}).get('total', 0)
        all_orders.extend(records)
        print(f'{len(records)}/{total} records ({elapsed:.1f}s)')
    except Exception as e:
        print(f'ERROR: {e}')
        continue

print(f'\nTotal orders fetched: {len(all_orders)}')

# Aggregate per device (use deviceNum as key, deviceName for display)
from collections import defaultdict
device_revenue = defaultdict(lambda: {'name': '', 'orders': 0, 'revenue': 0.0})

for o in all_orders:
    if o.get('state') != 'DONE':
        continue
    dn = o.get('deviceNum', 'UNKNOWN')
    name = o.get('deviceName', dn)
    amt = float(o.get('amountMoney') or 0)
    device_revenue[dn]['name'] = name
    device_revenue[dn]['orders'] += 1
    device_revenue[dn]['revenue'] += amt

# Sort by revenue desc
sorted_devices = sorted(device_revenue.items(), key=lambda x: x[1]['revenue'], reverse=True)

total_revenue = sum(d['revenue'] for _, d in sorted_devices)
total_orders = sum(d['orders'] for _, d in sorted_devices)

print(f'Devices with sales: {len(sorted_devices)}')
print(f'Total completed orders: {total_orders}')
print(f'Total revenue: ¥{total_revenue:,.2f}')

# Save as JSON for later Excel generation
with open('/tmp/v2_revenue_data.json', 'w') as f:
    json.dump({
        'devices': [(dn, d['name'], d['orders'], round(d['revenue'], 2)) for dn, d in sorted_devices],
        'totals': {'devices': len(sorted_devices), 'orders': total_orders, 'revenue': round(total_revenue, 2)}
    }, f, ensure_ascii=False)

print('\nTop 10 by revenue:')
for i, (dn, d) in enumerate(sorted_devices[:10]):
    print(f'  {i+1}. {d["name"]} — {d["orders"]}笔 ¥{d["revenue"]:,.2f}')
