#!/usr/bin/env python3
import urllib3; urllib3.disable_warnings()
"""Generate A-share sector report as HTML directly"""
import requests
import re
import json
import sys
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=30, verify=False)
    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=20, verify=False)
        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 []

STYLE = '''<style>
*{margin:0;padding:0;box-sizing:border-box}:root{--bg:#fff;--text:#1a1a1a;--text-secondary:#656d76;--border:#e8e8e8;--accent:#0969da;--code-bg:#f6f8fa}
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:var(--bg);color:var(--text);line-height:1.7;max-width:900px;margin:0 auto;padding:40px 24px}
a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}
.article-header{margin-bottom:32px;padding-bottom:24px;border-bottom:1px solid var(--border)}
.article-header h1{font-size:28px;font-weight:600;margin-bottom:8px}
.article-meta{color:var(--text-secondary);font-size:14px}
.article-tags{margin-top:8px}.article-tags span{background:var(--code-bg);padding:2px 8px;border-radius:4px;font-size:12px;margin-right:6px}
.article-content{font-size:15px}
.article-content h2{font-size:20px;font-weight:600;margin:32px 0 16px;padding-bottom:8px;border-bottom:1px solid var(--border)}
table{width:100%;border-collapse:collapse;margin:16px 0;font-size:14px}
th,td{border:1px solid var(--border);padding:10px 14px;text-align:left}
th{background:var(--code-bg);font-weight:600}
.back-link{display:inline-block;margin-bottom:16px;color:var(--accent)}
</style>'''

def make_table(rows, headers):
    html = '<table><thead><tr>'
    for h in headers:
        html += f'<th>{h}</th>'
    html += '</tr></thead><tbody>'
    for row in rows:
        html += '<tr>'
        for cell in row:
            html += f'<td>{cell}</td>'
        html += '</tr>'
    html += '</tbody></table>'
    return html

def main():
    sectors = get_cn_sectors()
    if not sectors:
        print("Error: 无法获取数据", file=sys.stderr)
        sys.exit(1)
    
    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')
    now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # Build gainers table
    gainer_rows = []
    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
        gainer_rows.append([
            str(i), s['f14'], f"{s.get('f3', 0):+.2f}%",
            f"{s.get('f7', 0):+.2f}%", f"{vol:.2f}亿", top
        ])
    
    # Build losers table
    loser_rows = []
    for i, s in enumerate(losers, 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
        loser_rows.append([
            str(i), s['f14'], f"{s.get('f3', 0):+.2f}%",
            f"{s.get('f7', 0):+.2f}%", f"{vol:.2f}亿", top
        ])
    
    # Build volume table
    vol_rows = []
    for i, s in enumerate(by_vol, 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
        vol_rows.append([
            str(i), s['f14'], f"{s.get('f3', 0):+.2f}%",
            f"{s.get('f7', 0):+.2f}%", f"{vol:.2f}亿", top
        ])
    
    headers = ['#', '板块', '涨跌幅', '5日涨跌', '成交额', '代表股']
    
    top3 = ", ".join([f"{s['f14']}({s['f3']:+.2f}%)" for s in gainers[:3]])
    worst3 = ", ".join([f"{s['f14']}({s['f3']:+.2f}%)" for s in losers[:3]])
    
    html = f'''<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>A股市场行业板块报告 {today}</title>{STYLE}</head>
<body>
<a class="back-link" href="/blog/">← Back to Index</a>
<article>
<div class="article-header">
<h1>📈 A股市场行业板块报告 — {today}</h1>
<div class="article-meta"><span>📅 {today}</span></div>
<div class="article-tags"><span>a股</span><span>china</span><span>stock</span><span>daily-report</span></div>
</div>
<div class="article-content">
<h2>🔥 今日涨幅前15板块</h2>
<p><strong>数据来源: 东方财富</strong></p>
{make_table(gainer_rows, headers)}

<h2>📉 今日相对弱势板块</h2>
{make_table(loser_rows, headers)}

<h2>💰 本周成交额最大板块</h2>
{make_table(vol_rows, headers)}

<h2>💡 简评</h2>
<ul>
<li><strong>领涨板块</strong>: {top3}</li>
<li><strong>相对弱势</strong>: {worst3}</li>
<li><strong>市场特征</strong>: 今日A股行业分化，成长板块相对强势</li>
</ul>
</div>
</article>
<p style="margin-top:40px;color:#656d76;font-size:14px">报告生成时间: {now}</p>
</body></html>'''
    
    return html

if __name__ == '__main__':
    print(main())
