#!/usr/bin/env python3
"""Generate A-share sector HTML directly on VPS"""
import requests
import re
import json
from datetime import datetime

def get_cn_sectors():
    url = 'https://push2delay.eastmoney.com/api/qt/clist/get'
    params = {
        'pn': 1, 'pz': 100, 'po': 1, 'np': 1, 'fltt': 2, 'invt': 2,
        'fid': 'f3', 'fs': 'm:90+t:2',
        'fields': 'f2,f3,f4,f6,f7,f12,f14'
    }
    resp = requests.get(url, params=params, timeout=15)
    text = resp.text
    m = re.search(r'jQuery\((.+)\)\s*;?\s*$', text, re.DOTALL)
    if m:
        json_str = m.group(1)
    else:
        json_str = text
    data = json.loads(json_str)
    return data['data']['diff']

def get_sector_stocks(code):
    url = 'https://push2delay.eastmoney.com/api/qt/clist/get'
    params = {
        'pn': 1, 'pz': 5, 'po': 1, 'np': 1, 'fltt': 2, 'invt': 2,
        'fid': 'f3', 'fs': f'b:{code}+t:2+f:!50',
        'fields': 'f2,f3,f4,f6,f12,f14'
    }
    try:
        resp = requests.get(url, params=params, timeout=10)
        text = resp.text
        m = re.search(r'jQuery\((.+)\)\s*;?\s*$', text, re.DOTALL)
        if m:
            json_str = m.group(1)
        else:
            json_str = text
        data = json.loads(json_str)
        return data['data']['diff'][:5]
    except:
        return []

sectors = get_cn_sectors()
gainers = sorted(sectors, key=lambda x: x.get('f3', 0), reverse=True)[:15]
losers = sorted(sectors, key=lambda x: x.get('f3', 0))[:15]
by_vol = sorted(sectors, key=lambda x: x.get('f6', 0), reverse=True)[:10]

today = datetime.now().strftime('%Y-%m-%d')

# Build HTML
html = f'''<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>A股报告 {today}</title></head>
<body>
<h1>📈 A股市场行业板块报告 — {today}</h1>
<p><strong>数据来源: 东方财富</strong></p>

<h2>🔥 今日涨幅前15板块</h2>
<table border="1">
<tr><th>#</th><th>板块</th><th>涨跌幅</th><th>5日涨跌</th><th>成交额</th><th>代表股</th></tr>
'''
for i, s in enumerate(gainers, 1):
    stocks = get_sector_stocks(s.get('f12', ''))
    top = stocks[0]['f14'] + f"({stocks[0]['f3']:+.2f}%)" if stocks else "—"
    vol = s.get('f6', 0) / 1e8
    html += f"<tr><td>{i}</td><td>{s['f14']}</td><td>{s.get('f3', 0):+.2f}%</td><td>{s.get('f7', 0):+.2f}%</td><td>{vol:.2f}亿</td><td>{top}</td></tr>\n"

html += '</table></body></html>'

with open('/var/www/blog/a-stock-test.html', 'w', encoding='utf-8') as f:
    f.write(html)
print('Written, length:', len(html))
print('Has 代表股:', '代表股' in html)
