import streamlit as st
import psycopg2
import psycopg2.extras
import os
from datetime import datetime, date, timedelta
import json
import random
from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib import colors
import io

# PostgreSQL database connection
def get_db_connection():
    """Get PostgreSQL database connection"""
    return psycopg2.connect(os.environ['DATABASE_URL'])

def main():
    st.set_page_config(
        page_title="SIM Analytics Dashboard",
        page_icon="📊",
        layout="wide"
    )
    
    st.title("📊 4G/5G SIM Card Usage Analytics")
    st.markdown("---")
    
    # Sidebar navigation
    st.sidebar.title("Navigation")
    page = st.sidebar.selectbox("Select Page", [
        "Dashboard",
        "Client Management", 
        "SIM Management",
        "Usage Data Entry",
        "Usage Analytics",
        "Protocol Analysis",
        "Reports"
    ])
    
    if page == "Dashboard":
        show_dashboard()
    elif page == "Client Management":
        show_client_management()
    elif page == "SIM Management":
        show_sim_management()
    elif page == "Usage Data Entry":
        show_usage_entry()
    elif page == "Usage Analytics":
        show_usage_analytics()
    elif page == "Protocol Analysis":
        show_protocol_analysis()
    elif page == "Reports":
        show_reports()

def show_dashboard():
    st.header("📈 Analytics Dashboard")
    
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    
    # Get statistics
    cursor.execute("SELECT COUNT(*) as count FROM clients")
    result = cursor.fetchone()
    total_clients = result['count'] if result else 0
    
    cursor.execute("SELECT COUNT(*) as count FROM usage_records")
    result = cursor.fetchone()
    total_records = result['count'] if result else 0
    
    cursor.execute("SELECT COALESCE(SUM(total_usage_gb), 0) as total FROM usage_records")
    result = cursor.fetchone()
    total_usage = result['total'] if result else 0
    
    cursor.execute("SELECT COUNT(*) as count FROM usage_records WHERE fup_reached = true")
    result = cursor.fetchone()
    fup_exceeded = result['count'] if result else 0
    
    # Display metrics
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric("Total Clients", total_clients)
    
    with col2:
        st.metric("Usage Records", total_records)
    
    with col3:
        st.metric("Total Usage (GB)", f"{total_usage:.2f}")
    
    with col4:
        st.metric("FUP Exceeded", fup_exceeded)
    
    st.markdown("---")
    
    # Individual SIM Statistics
    st.subheader("Individual SIM Card Statistics")
    cursor.execute("""
        SELECT ur.client_id, ur.sim_number, ur.msisdn, ur.total_usage_gb, 
               ur.date_from, ur.date_to, ur.fup_reached, c.client_name
        FROM usage_records ur
        JOIN clients c ON ur.client_id = c.client_id
        ORDER BY c.client_name, ur.sim_number, ur.created_at DESC
    """)
    sim_records = cursor.fetchall()
    
    if sim_records:
        # Group by client for better organization
        current_client = None
        for record in sim_records:
            if current_client != record['client_name']:
                current_client = record['client_name']
                st.write(f"### {current_client}")
            
            sim_display = record['sim_number'] if record['sim_number'] else record['client_id']
            msisdn_display = record['msisdn'] if record['msisdn'] else 'N/A'
            fup_status = "🔴 Exceeded" if record['fup_reached'] else "🟢 Normal"
            
            col1, col2, col3, col4 = st.columns(4)
            with col1:
                st.write(f"**SIM:** {sim_display}")
            with col2:
                st.write(f"**MSISDN:** {msisdn_display}")
            with col3:
                st.write(f"**Usage:** {record['total_usage_gb']} GB")
            with col4:
                st.write(f"**FUP:** {fup_status}")
            
            st.write(f"*Period: {record['date_from']} to {record['date_to']}*")
            st.markdown("---")
    else:
        st.info("No SIM usage records found.")
    
    st.markdown("---")
    
    # Recent usage records
    st.subheader("Recent Usage Records")
    cursor.execute("""
        SELECT ur.id, ur.client_id, ur.total_usage_gb, ur.sim_number, ur.msisdn,
               ur.date_from, ur.date_to, ur.fup_reached, ur.created_at, c.client_name 
        FROM usage_records ur
        JOIN clients c ON ur.client_id = c.client_id
        ORDER BY ur.created_at DESC
        LIMIT 10
    """)
    recent_records = cursor.fetchall()
    
    cursor.close()
    conn.close()
    
    if recent_records:
        for record in recent_records:
            sim_display = record['sim_number'] if record['sim_number'] else record['client_id']
            with st.expander(f"{record['client_name']} - {sim_display} ({record['total_usage_gb']} GB)"):
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.write(f"**Period:** {record['date_from']} to {record['date_to']}")
                with col2:
                    st.write(f"**MSISDN:** {record['msisdn'] or 'N/A'}")
                with col3:
                    st.write(f"**FUP Status:** {'Exceeded' if record['fup_reached'] else 'Normal'}")
    else:
        st.info("No usage records found. Add some data to get started.")

def show_client_management():
    st.header("👥 Client Management")
    
    # Add new client form
    with st.expander("Add New Client", expanded=True):
        with st.form("add_client"):
            client_name = st.text_input("Client Name")
            
            if st.form_submit_button("Add Client"):
                if client_name:
                    # Generate unique client ID based on name
                    import re
                    import secrets
                    
                    # Clean the name for ID generation
                    clean_name = re.sub(r'[^a-zA-Z0-9\s]', '', client_name)
                    name_parts = clean_name.strip().split()
                    
                    if len(name_parts) >= 2:
                        # Use first letter of first name + last name + random number
                        client_id = f"{name_parts[0][0].upper()}{name_parts[-1].capitalize()}{secrets.randbelow(9999):04d}"
                    else:
                        # Use name + random number
                        client_id = f"{clean_name.replace(' ', '')}{secrets.randbelow(9999):04d}"
                    
                    conn = get_db_connection()
                    cursor = conn.cursor()
                    try:
                        # Check if ID already exists and regenerate if needed
                        cursor.execute("SELECT COUNT(*) FROM clients WHERE client_id = %s", (client_id,))
                        if cursor.fetchone()[0] > 0:
                            # Add timestamp suffix if ID exists
                            import time
                            client_id = f"{client_id}_{int(time.time()) % 10000}"
                        
                        cursor.execute("INSERT INTO clients (client_id, client_name) VALUES (%s, %s)", 
                                     (client_id, client_name))
                        conn.commit()
                        st.success(f"Client '{client_name}' added successfully with ID: {client_id}")
                    except psycopg2.IntegrityError:
                        st.error("Error adding client. Please try again.")
                    finally:
                        cursor.close()
                        conn.close()
                else:
                    st.error("Please enter a client name.")
    
    # Display existing clients
    st.subheader("Existing Clients")
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cursor.execute("SELECT * FROM clients ORDER BY client_name")
    clients = cursor.fetchall()
    cursor.close()
    conn.close()
    
    if clients:
        for client in clients:
            st.write(f"**{client['client_name']}** (ID: {client['client_id']})")
    else:
        st.info("No clients found.")

def show_sim_management():
    st.header("📱 SIM Management")
    
    # Get clients for dropdown
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cursor.execute("SELECT client_id, client_name FROM clients ORDER BY client_name")
    clients = cursor.fetchall()
    cursor.close()
    conn.close()
    
    if not clients:
        st.warning("No clients found. Please add clients first.")
        return
    
    # Add new SIM form
    with st.expander("Add New SIM", expanded=True):
        with st.form("add_sim"):
            client_options = {f"{c['client_name']} ({c['client_id']})": c['client_id'] for c in clients}
            selected_client = st.selectbox("Select Client", options=list(client_options.keys()))
            sim_number = st.text_input("SIM Number")
            msisdn = st.text_input("MSISDN (Optional)")
            
            if st.form_submit_button("Add SIM"):
                if selected_client and sim_number:
                    client_id = client_options[selected_client]
                    conn = get_db_connection()
                    cursor = conn.cursor()
                    cursor.execute("INSERT INTO sim_numbers (client_id, sim_number, msisdn) VALUES (%s, %s, %s)",
                                 (client_id, sim_number, msisdn if msisdn else None))
                    conn.commit()
                    cursor.close()
                    conn.close()
                    st.success(f"SIM '{sim_number}' added successfully!")
                else:
                    st.error("Please fill in required fields.")
    
    # Display existing SIMs
    st.subheader("Existing SIM Cards")
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cursor.execute("""
        SELECT s.*, c.client_name 
        FROM sim_numbers s
        JOIN clients c ON s.client_id = c.client_id
        ORDER BY c.client_name, s.sim_number
    """)
    sims = cursor.fetchall()
    cursor.close()
    conn.close()
    
    if sims:
        for sim in sims:
            st.write(f"**{sim['sim_number']}** - {sim['client_name']} (MSISDN: {sim['msisdn'] or 'N/A'})")
    else:
        st.info("No SIM cards found.")

def show_usage_entry():
    st.header("📊 Usage Data Entry")
    
    # Get clients for dropdown
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cursor.execute("SELECT client_id, client_name FROM clients ORDER BY client_name")
    clients = cursor.fetchall()
    cursor.close()
    conn.close()
    
    if not clients:
        st.warning("No clients found. Please add clients first.")
        return
    
    with st.form("add_usage"):
        # Client selection
        client_options = {f"{c['client_name']} ({c['client_id']})": c['client_id'] for c in clients}
        selected_client = st.selectbox("Select Client", options=list(client_options.keys()))
        
        # Initialize variables
        selected_sim = None
        sim_options = {}
        
        # Get SIMs for selected client
        if selected_client:
            client_id = client_options[selected_client]
            conn = get_db_connection()
            cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
            cursor.execute("SELECT * FROM sim_numbers WHERE client_id = %s", (client_id,))
            sims = cursor.fetchall()
            cursor.close()
            conn.close()
            
            if sims:
                sim_options = {f"{s['sim_number']} (MSISDN: {s['msisdn'] or 'N/A'})": (s['sim_number'], s['msisdn']) for s in sims}
                selected_sim = st.selectbox("Select SIM", options=list(sim_options.keys()))
            else:
                st.warning("No SIM cards found for this client.")
                selected_sim = None
        
        # Usage data inputs
        col1, col2 = st.columns(2)
        with col1:
            date_from = st.date_input("Date From")
        with col2:
            date_to = st.date_input("Date To")
        
        total_usage_gb = st.number_input("Total Usage (GB)", min_value=0.0, step=0.1)
        fup_reached = st.checkbox("FUP Reached")
        
        if st.form_submit_button("Add Usage Record"):
            if selected_client and selected_sim and sim_options and total_usage_gb > 0:
                client_id = client_options[selected_client]
                sim_number, msisdn = sim_options[selected_sim]
                
                conn = get_db_connection()
                cursor = conn.cursor()
                cursor.execute("""
                    INSERT INTO usage_records 
                    (client_id, sim_number, msisdn, total_usage_gb, date_from, date_to, fup_reached)
                    VALUES (%s, %s, %s, %s, %s, %s, %s)
                """, (client_id, sim_number, msisdn, total_usage_gb, date_from, date_to, fup_reached))
                conn.commit()
                cursor.close()
                conn.close()
                st.success("Usage record added successfully!")
            else:
                st.error("Please fill in all required fields.")

def generate_daily_usage_data(total_usage_gb, date_from, date_to):
    """Generate random daily usage distribution"""
    start_date = datetime.strptime(str(date_from), '%Y-%m-%d').date()
    end_date = datetime.strptime(str(date_to), '%Y-%m-%d').date()
    
    # Convert decimal to float if needed
    total_usage_float = float(total_usage_gb)
    
    # Calculate number of days
    days = (end_date - start_date).days + 1
    
    # Generate random weights for each day
    weights = [random.uniform(0.5, 2.0) for _ in range(days)]
    total_weight = sum(weights)
    
    # Normalize weights to distribute total usage
    daily_usage = []
    dates = []
    
    for i in range(days):
        current_date = start_date + timedelta(days=i)
        usage = (weights[i] / total_weight) * total_usage_float
        daily_usage.append(usage)
        dates.append(current_date)
    
    return dates, daily_usage

def generate_usage_pdf(record, dates, daily_usage, protocol_data=None):
    """Generate comprehensive PDF report"""
    buffer = io.BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4)
    styles = getSampleStyleSheet()
    story = []
    
    # Title
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Heading1'],
        fontSize=18,
        spaceAfter=30,
        textColor=colors.HexColor('#1f4e79')
    )
    story.append(Paragraph(f"Usage Analytics Report", title_style))
    story.append(Spacer(1, 20))
    
    # Client Information
    client_info = [
        ['Client Name:', record['client_name']],
        ['SIM Number:', record['sim_number'] or 'N/A'],
        ['MSISDN:', record['msisdn'] or 'N/A'],
        ['Period:', f"{record['date_from']} to {record['date_to']}"],
        ['Total Usage:', f"{record['total_usage_gb']} GB"],
        ['FUP Status:', 'Exceeded' if record['fup_reached'] else 'Normal']
    ]
    
    client_table = Table(client_info, colWidths=[2*inch, 3*inch])
    client_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#f0f0f0')),
        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('GRID', (0, 0), (-1, -1), 1, colors.black)
    ]))
    
    story.append(Paragraph("Client Information", styles['Heading2']))
    story.append(client_table)
    story.append(Spacer(1, 30))
    
    # Daily Usage Table
    daily_data = [['Date', 'Usage (GB)']]
    for date, usage in zip(dates, daily_usage):
        daily_data.append([str(date), f"{usage:.2f}"])
    
    daily_table = Table(daily_data, colWidths=[2*inch, 2*inch])
    daily_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1f4e79')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, -1), 9),
        ('GRID', (0, 0), (-1, -1), 1, colors.black)
    ]))
    
    story.append(Paragraph("Daily Usage Breakdown", styles['Heading2']))
    story.append(daily_table)
    
    # Protocol data if available
    if protocol_data:
        story.append(Spacer(1, 30))
        story.append(Paragraph("Top Protocol Usage", styles['Heading2']))
        
        protocol_table_data = [['Protocol', 'Category', 'Usage (GB)', 'Percentage']]
        for protocol in protocol_data[:10]:
            protocol_table_data.append([
                protocol['protocol_name'],
                protocol['category'],
                f"{protocol['usage_gb']:.2f}",
                f"{protocol['percentage']:.1f}%"
            ])
        
        protocol_table = Table(protocol_table_data, colWidths=[1.5*inch, 1.5*inch, 1*inch, 1*inch])
        protocol_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1f4e79')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('GRID', (0, 0), (-1, -1), 1, colors.black)
        ]))
        
        story.append(protocol_table)
    
    # Build PDF
    doc.build(story)
    buffer.seek(0)
    return buffer

def show_usage_analytics():
    st.header("📈 Usage Analytics")
    
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cursor.execute("""
        SELECT ur.id, ur.client_id, ur.sim_number, ur.msisdn, ur.total_usage_gb, ur.date_from, ur.date_to, 
               ur.fup_reached, ur.created_at, c.client_name 
        FROM usage_records ur
        JOIN clients c ON ur.client_id = c.client_id
        ORDER BY ur.date_from DESC
    """)
    records = cursor.fetchall()
    cursor.close()
    conn.close()
    
    if not records:
        st.info("No usage records found.")
        return
    
    # Display usage records with daily breakdown and export
    for record in records:
        sim_display = record['sim_number'] if record['sim_number'] else record['client_id']
        with st.expander(f"{record['client_name']} - {sim_display} ({record['total_usage_gb']} GB)"):
            col1, col2, col3 = st.columns(3)
            with col1:
                st.write(f"**Client:** {record['client_name']}")
            with col2:
                st.write(f"**SIM:** {sim_display}")
            with col3:
                st.write(f"**MSISDN:** {record['msisdn'] or 'N/A'}")
            
            col1, col2 = st.columns(2)
            with col1:
                st.write(f"**Period:** {record['date_from']} to {record['date_to']}")
            with col2:
                st.write(f"**Total Usage:** {record['total_usage_gb']} GB")
            
            st.write(f"**FUP Status:** {'Exceeded' if record['fup_reached'] else 'Normal'}")
            
            # Generate daily usage data
            dates, daily_usage = generate_daily_usage_data(
                record['total_usage_gb'], 
                record['date_from'], 
                record['date_to']
            )
            
            # Display daily usage as a table
            st.subheader("Daily Usage Distribution")
            daily_df_data = []
            total_usage_float = float(record['total_usage_gb'])
            for date, usage in zip(dates, daily_usage):
                daily_df_data.append({
                    'Date': str(date),
                    'Usage (GB)': f"{usage:.2f}",
                    'Percentage': f"{(usage/total_usage_float*100):.1f}%"
                })
            
            # Create columns for daily usage display
            for i in range(0, len(daily_df_data), 3):
                cols = st.columns(3)
                for j, col in enumerate(cols):
                    if i + j < len(daily_df_data):
                        data = daily_df_data[i + j]
                        with col:
                            st.write(f"**{data['Date']}**")
                            st.write(f"{data['Usage (GB)']} ({data['Percentage']})")
            
            # Get protocol data for this record
            conn = get_db_connection()
            cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
            cursor.execute("""
                SELECT protocol_name, category, usage_gb, percentage
                FROM protocol_usage
                WHERE usage_record_id = %s
                ORDER BY usage_gb DESC
                LIMIT 10
            """, (record['id'],))
            protocol_data = cursor.fetchall()
            cursor.close()
            conn.close()
            
            # Export to PDF button
            if st.button(f"📄 Export to PDF", key=f"export_{record['id']}"):
                pdf_buffer = generate_usage_pdf(record, dates, daily_usage, protocol_data)
                
                st.download_button(
                    label="Download PDF Report",
                    data=pdf_buffer.getvalue(),
                    file_name=f"usage_report_{record['client_name'].replace(' ', '_')}_{record['date_from']}.pdf",
                    mime="application/pdf",
                    key=f"download_{record['id']}"
                )

def show_protocol_analysis():
    st.header("🔍 Protocol Analysis")
    
    # Get all usage records with protocol data
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    
    # Client selection
    cursor.execute("SELECT DISTINCT client_id, client_name FROM clients ORDER BY client_name")
    clients = cursor.fetchall()
    
    if not clients:
        st.warning("No clients found.")
        return
    
    # Add "All Clients" option
    client_options = ["All Clients"] + [f"{c['client_name']} ({c['client_id']})" for c in clients]
    selected_client = st.selectbox("Select Client", client_options)
    
    if selected_client == "All Clients":
        # Show protocol analysis for all clients
        cursor.execute("""
            SELECT pu.protocol_name, pu.category, SUM(pu.usage_gb) as total_usage_gb, 
                   AVG(pu.percentage) as avg_percentage
            FROM protocol_usage pu
            JOIN usage_records ur ON pu.usage_record_id = ur.id
            GROUP BY pu.protocol_name, pu.category
            ORDER BY total_usage_gb DESC
        """)
        protocol_data = cursor.fetchall()
        
        st.subheader("Overall Protocol Usage")
        
        if protocol_data:
            # Display top protocols
            st.write("**Top 10 Protocols by Usage:**")
            for i, protocol in enumerate(protocol_data[:10]):
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.write(f"{i+1}. **{protocol['protocol_name']}**")
                with col2:
                    st.write(f"{protocol['total_usage_gb']:.2f} GB")
                with col3:
                    st.write(f"Category: {protocol['category']}")
            
            # Category breakdown
            st.markdown("---")
            st.subheader("Usage by Category")
            cursor.execute("""
                SELECT pu.category, SUM(pu.usage_gb) as total_usage_gb
                FROM protocol_usage pu
                GROUP BY pu.category
                ORDER BY total_usage_gb DESC
            """)
            category_data = cursor.fetchall()
            
            for category in category_data:
                st.write(f"**{category['category']}:** {category['total_usage_gb']:.2f} GB")
        else:
            st.info("No protocol data found.")
    
    else:
        # Show protocol analysis for specific client
        client_id = selected_client.split('(')[1].strip(')')
        
        cursor.execute("""
            SELECT ur.id, ur.sim_number, ur.msisdn, ur.total_usage_gb, ur.date_from, ur.date_to
            FROM usage_records ur
            WHERE ur.client_id = %s
            ORDER BY ur.created_at DESC
        """, (client_id,))
        usage_records = cursor.fetchall()
        
        if not usage_records:
            st.info("No usage records found for this client.")
            cursor.close()
            conn.close()
            return
        
        st.subheader(f"Protocol Analysis for {selected_client}")
        
        for record in usage_records:
            sim_display = record['sim_number'] if record['sim_number'] else 'N/A'
            msisdn_display = record['msisdn'] if record['msisdn'] else 'N/A'
            
            with st.expander(f"SIM: {sim_display} | MSISDN: {msisdn_display} | {record['total_usage_gb']} GB ({record['date_from']} to {record['date_to']})"):
                cursor.execute("""
                    SELECT protocol_name, category, usage_gb, percentage
                    FROM protocol_usage
                    WHERE usage_record_id = %s
                    ORDER BY usage_gb DESC
                """, (record['id'],))
                protocols = cursor.fetchall()
                
                if protocols:
                    # Top protocols for this record
                    st.write("**Top Protocols:**")
                    for i, protocol in enumerate(protocols[:10]):
                        col1, col2, col3, col4 = st.columns(4)
                        with col1:
                            st.write(f"{i+1}. {protocol['protocol_name']}")
                        with col2:
                            st.write(f"{protocol['usage_gb']:.2f} GB")
                        with col3:
                            st.write(f"{protocol['percentage']:.1f}%")
                        with col4:
                            st.write(protocol['category'])
                    
                    # Category summary for this record
                    cursor.execute("""
                        SELECT category, SUM(usage_gb) as total_gb, SUM(percentage) as total_percentage
                        FROM protocol_usage
                        WHERE usage_record_id = %s
                        GROUP BY category
                        ORDER BY total_gb DESC
                    """, (record['id'],))
                    categories = cursor.fetchall()
                    
                    st.write("**Category Breakdown:**")
                    for cat in categories:
                        st.write(f"- **{cat['category']}:** {cat['total_gb']:.2f} GB ({cat['total_percentage']:.1f}%)")
                else:
                    st.info("No protocol data available for this usage record.")
    
    cursor.close()
    conn.close()

def show_reports():
    st.header("📄 Reports")
    st.info("Additional report generation features available through PDF export in Usage Analytics.")

if __name__ == "__main__":
    main()