#!/usr/bin/env python3
"""Generate standalone correlation.html"""
import json, sys, os
_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, _ROOT)
from tools.macro_correlation import analyze

def generate():
    data = analyze()
    syms = data.get('symbols', [])
    labels = data.get('labels', {})
    matrix = data.get('correlation_matrix', {})
    prices = data.get('prices', {})
    vols = data.get('volatilities', {})
    hedge = data.get('hedge_suggestions', [])

    # Correlation matrix rows
    rows = ''
    for si in syms:
        rows += '<tr><td class="lbl">%s</td>' % labels.get(si, si)
        for sj in syms:
            v = matrix.get(si, {}).get(sj, 0)
            a = abs(v)
            bg = 'rgba(63,185,80,%s)' % str(round(a,2)) if v>0 else 'rgba(248,81,73,%s)' % str(round(a,2))
            rows += '<td style="background:%s;text-align:center;padding:8px;font-size:11px;font-weight:600">%.3f</td>' % (bg, v)
        rows += '</tr>'

    # Volatility rows
    vol_rows = ''
    for s in sorted(vols, key=lambda x: -vols[x]):
        vol_rows += '<tr><td>%s</td><td style="text-align:right;font-weight:600">%.1f%%</td></tr>' % (labels.get(s, s), vols[s])

    # Hedge rows
    hedge_rows = ''
    for h in hedge[:10]:
        c = '#22c55e' if h['quality']=='Excellent' else '#f59e0b' if h['quality']=='Good' else '#64748b'
        hedge_rows += '<tr><td>%s</td><td style="text-align:center">%.3f</td><td style="color:%s;font-weight:600;text-align:center">%s</td><td style="text-align:center;font-weight:600">%.1f%%</td></tr>' % (
            h['label'], h['corr'], c, h['quality'], h['weight'])

    # Price rows
    price_rows = ''
    for s in syms:
        p = prices.get(s, 0)
        price_rows += '<tr><td>%s</td><td style="text-align:right;font-weight:600">$%.2f</td></tr>' % (labels.get(s, s), p)

    html = '''<!DOCTYPE html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Correlation & Hedge</title>
<style>
:root{--bg:#0a0e14;--card:#11161e;--border:#1e293b;--text:#e2e8f0;--muted:#64748b;--green:#22c55e;--red:#ef4444}
*{margin:0;padding:0;box-sizing:border-box}
body{background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,sans-serif;font-size:13px;padding:20px;max-width:1400px;margin:0 auto}
h1{font-size:18px;margin-bottom:4px}
.sub{color:var(--muted);font-size:11px;margin-bottom:24px}
.card{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:18px;margin-bottom:16px}
.card h2{font-size:12px;color:var(--muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:.8px}
table{width:100%;border-collapse:collapse}
th,td{padding:6px 10px;border-bottom:1px solid var(--border);font-size:11px}
th{color:var(--muted);text-align:left;font-size:10px;font-weight:500}
td.lbl{color:var(--text);font-weight:600}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:900px){.grid2{grid-template-columns:1fr}}
a.back{color:var(--muted);text-decoration:none;font-size:12px}
a.back:hover{color:var(--text)}
.badge{display:inline-block;padding:2px 8px;border-radius:4px;font-size:10px;font-weight:600;color:#fff}
</style></head><body>
<a href="/" class="back">&larr; Dashboard</a>
<h1>Multi-Asset Correlation & Hedge</h1>
<div class="sub">1-Week 1H Bars &middot; Generated: ''' + data['timestamp'] + ''' BJT &middot; ''' + str(len(syms)) + ''' assets</div>

<div class="card">
<h2>Correlation Matrix</h2>
<div style="overflow-x:auto"><table>
<tr><th></th>''' + ''.join('<th>%s</th>' % labels.get(s, s) for s in syms) + '''</tr>''' + rows + '''</table></div>
</div>

<div class="grid2">
<div class="card">
<h2>Hedge Allocation vs BTC</h2>
<table>
<tr><th>Asset</th><th style="text-align:center">Corr</th><th style="text-align:center">Quality</th><th style="text-align:center">Weight</th></tr>''' + hedge_rows + '''</table>
</div>
<div class="card">
<h2>Asset Prices & Volatility</h2>
<div class="grid2">
<div>
<h2 style="margin-top:0">Prices</h2>
<table><tr><th>Asset</th><th style="text-align:right">Price</th></tr>''' + price_rows + '''</table>
</div>
<div>
<h2 style="margin-top:0">Volatility (Ann.)</h2>
<table><tr><th>Asset</th><th style="text-align:right">Vol %</th></tr>''' + vol_rows + '''</table>
</div>
</div>
</div>
</div>
</body></html>'''

    out_path = os.path.join(_ROOT, 'dashboard', 'correlation_static.html')
    with open(out_path, 'w', encoding='utf-8') as f:
        f.write(html)
    print('Generated correlation_static.html (%d KB)' % (os.path.getsize(out_path)//1024))


if __name__ == '__main__':
    generate()
