import os
import datetime
from collections import defaultdict
import customer_db

def generate_report():
    customers = customer_db._db.get_all_customers()
    events = customer_db._db.get_recent_events(limit=10000)
    
    total_events = len(events)
    blocked_events = sum(1 for e in events if e.get('outcome') == 'block')
    block_rate = (blocked_events / total_events * 100) if total_events else 0
    total_mrr = sum(c.get('mrr', 0) for c in customers)
    
    latencies = [e.get('latency_ms', 0) for e in events if e.get('latency_ms') is not None]
    avg_latency = sum(latencies) / len(latencies) if latencies else 0

    bots = defaultdict(lambda: {'total': 0, 'blocked': 0})
    ips = defaultdict(int)

    for e in events:
        bot_class = e.get('bot_class') or 'unknown'
        bots[bot_class]['total'] += 1
        if e.get('outcome') == 'block':
            bots[bot_class]['blocked'] += 1
        ip_addr = e.get('ip_address') or e.get('ip') or 'unknown'
        ips[ip_addr] += 1

    top_ips = sorted(ips.items(), key=lambda x: x[1], reverse=True)[:10]

    report_dir = "/home/snuffleupagus/teamwork_projects/axiom_zero_audit/reports"
    os.makedirs(report_dir, exist_ok=True)
    today = datetime.datetime.now().strftime("%Y-%m-%d")
    report_path = os.path.join(report_dir, f"axiom_daily_{today}.html")

    html = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Axiom Zero - Executive Report</title>
    <style>
        body {{
            background-color: #060911;
            color: #F1F5F9;
            font-family: system-ui, -apple-system, sans-serif;
            margin: 0;
            padding: 20px;
        }}
        .banner {{
            background-color: #D4AF37;
            color: #060911;
            text-align: center;
            font-weight: bold;
            padding: 10px;
            margin-bottom: 20px;
        }}
        .header {{ margin-bottom: 30px; }}
        .header h1 {{ margin: 0; color: #D4AF37; }}
        .kpi-grid {{
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }}
        .card {{
            background: #111827;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #D4AF37;
        }}
        .card h3 {{ margin-top: 0; font-size: 14px; color: #9CA3AF; }}
        .card .value {{ font-size: 24px; font-weight: bold; }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }}
        th, td {{
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #374151;
        }}
        th {{ color: #D4AF37; }}
        .status-valid {{ color: #10B981; }}
        .status-invalid {{ color: #EF4444; }}
    </style>
</head>
<body>
    <div class="banner">AXIOM ZERO — INTERNAL EXECUTIVE REPORT — CONFIDENTIAL</div>
    <div class="header">
        <h1>Axiom Zero</h1>
        <div>Daily Executive Report</div>
        <div>Generated: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</div>
    </div>
    
    <div class="kpi-grid">
        <div class="card">
            <h3>Block Rate</h3>
            <div class="value">{block_rate:.1f}%</div>
        </div>
        <div class="card">
            <h3>Total Events</h3>
            <div class="value">{total_events}</div>
        </div>
        <div class="card">
            <h3>Monthly Revenue</h3>
            <div class="value">${total_mrr:,}</div>
        </div>
        <div class="card">
            <h3>Avg Latency</h3>
            <div class="value">{avg_latency:.1f} ms</div>
        </div>
    </div>

    <h2 style="color: #D4AF37;">Customer Status</h2>
    <table>
        <tr>
            <th>Company</th>
            <th>Tier</th>
            <th>MRR</th>
            <th>Credential Status</th>
        </tr>
"""
    for c in customers:
        status = c.get("credential_status", "PENDING")
        status_class = "status-valid" if status == "VALID" else "status-invalid"
        html += f"""
        <tr>
            <td>{c.get('company_name', 'Unknown')}</td>
            <td>{c.get('tier', 'Unknown')}</td>
            <td>${c.get('mrr', 0):,}</td>
            <td class="{status_class}">{status}</td>
        </tr>
"""
    
    html += """
    </table>
    
    <h2 style="color: #D4AF37;">Detection Breakdown</h2>
    <table>
        <tr>
            <th>Bot Class</th>
            <th>Total Events</th>
            <th>Blocked</th>
            <th>Block Rate</th>
        </tr>
"""
    for bot, data in bots.items():
        rate = (data['blocked'] / data['total'] * 100) if data['total'] else 0
        html += f"""
        <tr>
            <td>{bot}</td>
            <td>{data['total']}</td>
            <td>{data['blocked']}</td>
            <td>{rate:.1f}%</td>
        </tr>
"""
    
    html += """
    </table>

    <h2 style="color: #D4AF37;">Top 10 Threat IPs</h2>
    <table>
        <tr>
            <th>IP Address</th>
            <th>Event Count</th>
        </tr>
"""
    for ip, count in top_ips:
        html += f"""
        <tr>
            <td>{ip}</td>
            <td>{count}</td>
        </tr>
"""
    
    html += f"""
    </table>
    
    <div style="text-align: center; color: #6B7280; font-size: 12px; margin-top: 50px;">
        CONFIDENTIAL - GENERATED {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
    </div>
</body>
</html>
"""
    with open(report_path, "w") as f:
        f.write(html)
    
    print(f"Report generated successfully: {report_path}")

if __name__ == "__main__":
    generate_report()
