import json
from datetime import datetime


def create_beautiful_html_from_json(json_data):
    """
    Converts the message analytics JSON data into a beautiful HTML report
    """

    # Parse JSON if it's a string
    if isinstance(json_data, str):
        data = json.loads(json_data)
    else:
        data = json_data

    # Calculate additional metrics
    total_attempts = data.get('total_transmissions', 0)
    success_rate = data.get('success_rate', 0)
    failure_rate = data.get('failure_rate', 0)

    # Build HTML
    html = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Message Analytics Report</title>
        <style>
           * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 25%, #0f0f0f 50%, #000000 100%);
            background-attachment: fixed;
            min-height: 100vh;
            padding: 20px;
            color: #b0b0b0;
        }}

        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(10, 10, 10, 0.98);
            border-radius: 2px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.8);
            overflow: hidden;
            backdrop-filter: blur(10px);
            border: 1px solid #2a2a2a;
        }}

        .header {{
            background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 50%, #252525 100%);
            color: #d0d0d0;
            padding: 30px;
            text-align: center;
            position: relative;
            border-bottom: 2px solid #3a3a3a;
        }}

        .header::before {{
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: repeating-linear-gradient(
                45deg,
                transparent,
                transparent 2px,
                rgba(60, 60, 60, 0.1) 2px,
                rgba(60, 60, 60, 0.1) 4px
            );
            opacity: 0.3;
        }}

        .header h1 {{
            font-size: 2.5em;
            font-weight: 700;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
            text-transform: uppercase;
            letter-spacing: 2px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
            color: #e0e0e0;
        }}

        .header .subtitle {{
            font-size: 1.1em;
            opacity: 0.9;
            position: relative;
            z-index: 1;
            text-transform: uppercase;
            font-weight: 500;
            letter-spacing: 1px;
            color: #808080;
        }}

        .stats-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            padding: 30px;
            background: #0a0a0a;
            border-bottom: 1px solid #2a2a2a;
        }}

        .stat-card {{
            background: linear-gradient(145deg, #1a1a1a, #252525);
            border-radius: 2px;
            padding: 25px;
            text-align: center;
            box-shadow:
                0 10px 30px rgba(0, 0, 0, 0.5),
                inset 0 1px 0 rgba(255, 255, 255, 0.05);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            border: 1px solid #3a3a3a;
        }}

        .stat-card::before {{
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--accent-color);
            box-shadow: 0 0 10px var(--accent-color);
        }}

        .stat-card::after {{
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, var(--accent-color) 0%, transparent 70%);
            opacity: 0.05;
            pointer-events: none;
        }}

        .stat-card:hover {{
            transform: translateY(-3px);
            box-shadow:
                0 15px 40px rgba(0, 0, 0, 0.6),
                0 0 20px rgba(var(--accent-rgb), 0.3);
            border-color: var(--accent-color);
        }}

        .stat-card.success {{
            --accent-color: #808080;
            --accent-rgb: 128, 128, 128;
        }}

        .stat-card.failure {{
            --accent-color: #cc0000;
            --accent-rgb: 204, 0, 0;
        }}

        .stat-card.info {{
            --accent-color: #6a6a6a;
            --accent-rgb: 106, 106, 106;
        }}

        .stat-value {{
            font-size: 2.5em;
            font-weight: bold;
            color: var(--accent-color);
            margin-bottom: 10px;
            text-shadow: 0 0 10px rgba(var(--accent-rgb), 0.5);
            font-family: 'Consolas', monospace;
        }}

        .stat-label {{
            font-size: 1.1em;
            color: #909090;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
        }}

        .progress-bar {{
            width: 100%;
            height: 8px;
            background: #1a1a1a;
            border-radius: 1px;
            margin-top: 15px;
            overflow: hidden;
            border: 1px solid #3a3a3a;
        }}

        .progress-fill {{
            height: 100%;
            background: linear-gradient(90deg, var(--accent-color), rgba(var(--accent-rgb), 0.8));
            border-radius: 1px;
            transition: width 0.8s ease;
            box-shadow: 0 0 10px rgba(var(--accent-rgb), 0.6);
        }}

        .content-section {{
            padding: 30px;
            background: #0a0a0a;
        }}

        .section-title {{
            font-size: 1.8em;
            color: #d0d0d0;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 3px solid #3a3a3a;
            display: inline-block;
            text-transform: uppercase;
            font-weight: 700;
            letter-spacing: 1px;
        }}

        .message-card {{
            background: linear-gradient(145deg, #1a1a1a, #252525);
            border-radius: 2px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow:
                0 5px 15px rgba(0, 0, 0, 0.5),
                inset 0 1px 0 rgba(255, 255, 255, 0.05);
            border-left: 4px solid #3a3a3a;
            border: 1px solid #3a3a3a;
        }}

        .message-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 10px;
        }}

        .message-id {{
            font-family: 'Consolas', 'Monaco', monospace;
            background: #0f0f0f;
            padding: 5px 10px;
            border-radius: 2px;
            font-size: 0.9em;
            color: #909090;
            border: 1px solid #3a3a3a;
            text-transform: uppercase;
            font-weight: 600;
            letter-spacing: 1px;
        }}

        .message-time {{
            color: #808080;
            font-size: 0.95em;
            font-family: 'Consolas', monospace;
            font-weight: 500;
        }}

        .message-text {{
            background: #0f0f0f;
            padding: 15px;
            border-radius: 2px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 0.95em;
            color: #c0c0c0;
            white-space: pre-wrap;
            margin-bottom: 15px;
            border: 1px solid #2a2a2a;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.4);
        }}

        .status-grid {{
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 20px;
        }}

        .status-section {{
            background: linear-gradient(145deg, #1a1a1a, #252525);
            padding: 20px;
            border-radius: 2px;
            border: 1px solid #3a3a3a;
            box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05);
        }}

        .status-section h4 {{
            margin-bottom: 15px;
            color: #d0d0d0;
            text-transform: uppercase;
            font-weight: 700;
            letter-spacing: 1px;
            font-size: 1.1em;
        }}

        .status-section.success {{
            border-left: 4px solid #808080;
            box-shadow:
                inset 0 1px 0 rgba(255, 255, 255, 0.05),
                0 0 20px rgba(128, 128, 128, 0.1);
        }}

        .status-section.failure {{
            border-left: 4px solid #cc0000;
            box-shadow:
                inset 0 1px 0 rgba(255, 255, 255, 0.05),
                0 0 20px rgba(204, 0, 0, 0.2);
        }}

        .device-list {{
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }}

        .device-tag {{
            background: #3a3a3a;
            color: #c0c0c0;
            padding: 6px 12px;
            border-radius: 2px;
            font-size: 0.85em;
            font-family: 'Consolas', 'Monaco', monospace;
            border: 1px solid #4a4a4a;
            text-transform: uppercase;
            font-weight: 600;
            letter-spacing: 0.5px;
            transition: all 0.2s ease;
        }}

        .device-tag:hover {{
            background: #4a4a4a;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
        }}

        .device-tag.success {{
            background: #505050;
            border-color: #6a6a6a;
            color: #d0d0d0;
            box-shadow: 0 0 10px rgba(80, 80, 80, 0.3);
        }}

        .device-tag.failure {{
            background: #cc0000;
            border-color: #aa0000;
            color: #ffcccc;
            box-shadow: 0 0 10px rgba(204, 0, 0, 0.4);
        }}

        .footer {{
            background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 100%);
            color: #808080;
            text-align: center;
            padding: 20px;
            font-size: 0.9em;
            border-top: 1px solid #2a2a2a;
            font-family: 'Consolas', monospace;
            text-transform: uppercase;
            font-weight: 500;
            letter-spacing: 1px;
        }}

        /* Military-style animations */
        @keyframes radar-sweep {{
            0% {{ transform: rotate(0deg); }}
            100% {{ transform: rotate(360deg); }}
        }}

        .stat-card:hover::after {{
            animation: radar-sweep 2s linear infinite;
        }}

        /* Responsive design */
        @media (max-width: 768px) {{
            .stats-grid {{
                grid-template-columns: 1fr;
            }}

            .status-grid {{
                grid-template-columns: 1fr;
            }}

            .message-header {{
                flex-direction: column;
                align-items: flex-start;
            }}

            .header h1 {{
                font-size: 2em;
            }}
        }} 
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>📡 Message Analytics Report</h1>
                <div class="subtitle">Communication System Performance Dashboard</div>
            </div>

            <div class="stats-grid">
                <div class="stat-card success">
                    <div class="stat-value">{data.get('success_count', 0)}</div>
                    <div class="stat-label">Successful Transmissions</div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: {success_rate}%"></div>
                    </div>
                </div>

                <div class="stat-card failure">
                    <div class="stat-value">{data.get('failure_count', 0)}</div>
                    <div class="stat-label">Failed Transmissions</div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: {failure_rate}%"></div>
                    </div>
                </div>

                <div class="stat-card info">
                    <div class="stat-value">{data.get('total_messages', 0)}</div>
                    <div class="stat-label">Total Messages</div>
                </div>

                <div class="stat-card info">
                    <div class="stat-value">{total_attempts}</div>
                    <div class="stat-label">Total Transmissions</div>
                </div>
            </div>
    """

    # Add message details if available
    if data.get('front_hauled_messages'):
        html += """
            <div class="content-section">
                <h2 class="section-title">📨 Message Details</h2>
        """

        for message in data['front_hauled_messages']:
            # Format the message text
            message_text = message.get('text', '').replace('\\n', '\n')

            # Get message timestamp
            date_sent = message.get('dateSent', 'Unknown')
            mt_datetime = message.get('mtDateTime', 'Unknown')

            html += f"""
                <div class="message-card">
                    <div class="message-header">
                        <div class="message-id">ID: {message.get('id', 'Unknown')[:8]}...</div>
                        <div class="message-time">📅 {date_sent}</div>
                    </div>

                    <div class="message-text">{message_text}</div>

                    <div style="margin-bottom: 15px;">
                        <strong>Sender:</strong> {message.get('sender', 'Unknown')[:8]}...<br>
                        <strong>Conversation:</strong> {message.get('conversation', 'Unknown')[:8]}...<br>
                        <strong>Channel:</strong> {message.get('sentByChannelValue', 'Unknown')}<br>
                        <strong>Status:</strong> {message.get('stateValue', 'Unknown')}
                    </div>
            """

            # Add transmission status if available
            message_key = message.get('key', '')
            if message_key in data.get('successful_messages', {}) or message_key in data.get('failed_messages', {}):
                html += '<div class="status-grid">'

                # Successful devices
                successful_devices = data.get('successful_messages', {}).get(message_key, [])
                if successful_devices:
                    html += f"""
                        <div class="status-section success">
                            <h4>✅ Successful Transmissions ({len(successful_devices)})</h4>
                            <div class="device-list">
                    """
                    for device in successful_devices:
                        html += f'<span class="device-tag success">{device}</span>'
                    html += '</div></div>'

                # Failed devices
                failed_devices = data.get('failed_messages', {}).get(message_key, [])
                if failed_devices:
                    html += f"""
                        <div class="status-section failure">
                            <h4>❌ Failed Transmissions ({len(failed_devices)})</h4>
                            <div class="device-list">
                    """
                    for device in failed_devices:
                        html += f'<span class="device-tag failure">{device}</span>'
                    html += '</div></div>'

                html += '</div>'

            html += '</div>'

        html += '</div>'

    # Close HTML
    html += f"""
            <div class="footer">
                Generated on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | 
                Success Rate: {success_rate:.1f}% | 
                Total Transmissions: {total_attempts}
            </div>
        </div>

        <script>
            // Add smooth animations on load
            document.addEventListener('DOMContentLoaded', function() {{
                const cards = document.querySelectorAll('.stat-card');
                cards.forEach((card, index) => {{
                    setTimeout(() => {{
                        card.style.opacity = '1';
                        card.style.transform = 'translateY(0)';
                    }}, index * 100);
                }});
            }});
        </script>
    </body>
    </html>
    """

    return html


# Example usage function
def generate_transmission_report_html(json_file_path=None, json_string=None, output_file='message_report.html'):
    """
    Generate HTML report from JSON data

    Args:
        json_file_path: Path to JSON file
        json_string: JSON data as string
        output_file: Output HTML file name
    """

    if json_file_path:
        with open(json_file_path, 'r') as f:
            json_data = json.load(f)
    elif json_string:
        json_data = json.loads(json_string)
    else:
        # Sample data for demonstration
        json_data = {
            "success_count": 100,
            "failure_count": 35,
            "success_rate": 74.07407407407408,
            "failure_rate": 25.925925925925924,
            "total_messages": 27,
            "front_hauled_messages": [
                {
                    "id": "861228b0-7379-4919-9bcd-dc028a4834a7",
                    "text": "Test message from 11 \\n 456d98ec-2162-407a-ae75-9619cd6ac356 ",
                    "dateSent": "2025-05-23 15:11:53",
                    "mtDateTime": "Fri May 23 15:11:52 PDT 2025",
                    "sender": "85576b75-be28-4821-85b8-4e04bf6caf42",
                    "conversation": "15e193b8-8456-4e92-8c2b-c875ac94f778",
                    "parcelId": 767940816,
                    "readDate": "null",
                    "stateValue": "Received",
                    "sentByChannelValue": "Radio",
                    "userInitiatedCancel": 0,
                    "typeValue": "Text",
                    "uid": "null",
                    "markerTitle": "null",
                    "sosSessionId": "null",
                    "casevacPreviewLatitude": None,
                    "casevacPreviewLongitude": None,
                    "key": "1748038313000"
                }
            ],
            "total_transmissions": 135,
            "failed_messages": {
                "1748038313000": [
                    "RFCN90ZVEXP",
                    "R52T704P3RN",
                    "RFCR70KP6ZP"
                ]
            },
            "successful_messages": {
                "1748038313000": [
                    "23221JEGR11141",
                    "RFCN901AZVL"
                ]
            }
        }

    html_content = create_beautiful_html_from_json(json_data)

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_content)

    print(f"HTML report generated: {output_file}")
    return html_content


# Example usage:
if __name__ == "__main__":
    # Generate report with sample data
    html_output = generate_transmission_report_html()

    # Or generate from JSON file:
    # html_output = generate_html_report(json_file_path='your_data.json')

    # Or generate from JSON string:
    # html_output = generate_html_report(json_string='{"your": "json_data"}')