import os
import sys
import json
import sqlite3
import datetime
import psutil
from flask import Flask, render_code, render_template_string, jsonify

try:
    import GPUtil
except ImportError:
    GPUtil = None

app = Flask(__name__)

# ==========================================
# GALAXY THEME COLOR PALETTE
# ==========================================
GALAXY_BG = "#0B0E14"      # Deep space background
PANEL_BG = "#151B23"       # Nebula card/panel background
ACCENT_CYAN = "#00F0FF"    # Neon star cyan
ACCENT_PURPLE = "#9D4EDD"  # Deep nebula purple
TEXT_MAIN = "#E6EDF3"      # Bright starlight text
TEXT_MUTED = "#8B949E"     # Dim cosmic dust text
TERM_GREEN = "#00FF66"     # Terminal hacker green

# ==========================================
# REFERENCE DICTIONARIES
# ==========================================
PYTHON_REFERENCE_DICT = {
    "Control Flow & Conditionals": {
        "if": "Starts a conditional statement. Executes code if a condition is true.",
        "elif": 'Short for "else if". Checks another condition if the previous ones were false.',
        "else": "Executes a block of code if all previous conditions in an if/elif chain are false."
    },
    "Loops & Iteration": {
        "for": "Starts a loop that iterates over a sequence (like a list, tuple, or string).",
        "while": "Starts a loop that repeats as long as a specified condition remains true.",
        "break": "Immediately terminates the current loop and jumps to the code after it.",
        "continue": "Skips the rest of the current loop iteration and moves to the next turn."
    }
}

CPP_REFERENCE_DICT = {
    "Fundamental Types": {
        "bool": "Declares a variable that stores a boolean value (true or false).",
        "char": "Declares a single-byte character variable."
    }
}

# ==========================================
# VISUAL HTML FRONTEND TEMPLATE
# ==========================================
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CashWorkspace Engine</title>
    <style>
        body {
            background-color: {{ GALAXY_BG }};
            color: {{ TEXT_MAIN }};
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        header {
            border-bottom: 2px solid {{ ACCENT_PURPLE }};
            padding-bottom: 10px;
            margin-bottom: 30px;
            text-align: center;
        }
        h1 {
            color: {{ ACCENT_CYAN }};
            margin: 0;
            font-size: 2.5rem;
            text-transform: uppercase;
            letter-spacing: 2px;
        }
        .subtitle {
            color: {{ TEXT_MUTED }};
            margin-top: 5px;
        }
        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .card {
            background-color: {{ PANEL_BG }};
            border: 1px solid #222;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.5);
        }
        h2 {
            color: {{ ACCENT_PURPLE }};
            margin-top: 0;
            border-bottom: 1px solid #333;
            padding-bottom: 5px;
        }
        .stat-line {
            margin: 12px 0;
            font-size: 1.1rem;
        }
        .stat-value {
            color: {{ TERM_GREEN }};
            font-family: 'Courier New', Courier, monospace;
            font-weight: bold;
        }
        .ref-box {
            max-height: 300px;
            overflow-y: auto;
            padding-right: 5px;
        }
        .ref-category {
            font-weight: bold;
            color: {{ ACCENT_CYAN }};
            margin-top: 15px;
        }
        .ref-item {
            margin-left: 15px;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }
        .ref-key {
            color: {{ TERM_GREEN }};
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>CashWorkspace Dashboard</h1>
            <p class="subtitle">Systems Online Engine v1.0.0</p>
        </header>

        <div class="grid">
            <!-- SYSTEM METRICS CARD -->
            <div class="card">
                <h2>Server Live Telemetry</h2>
                <div class="stat-line">CPU Usage: <span class="stat-value">{{ cpu }}%</span></div>
                <div class="stat-line">RAM Usage: <span class="stat-value">{{ ram }}%</span></div>
                <div class="stat-line">OS Platform: <span class="stat-value">{{ platform }}</span></div>
                <div class="stat-line">Core Timestamp: <span class="stat-value">{{ timestamp }}</span></div>
            </div>

            <!-- CODE DICTIONARY REFERENCE CARD -->
            <div class="card">
                <h2>Python Syntax Dictionary</h2>
                <div class="ref-box">
                    {% for cat, items in ref_dict.items() %}
                        <div class="ref-category">{{ cat }}</div>
                        {% for key, val in items.items() %}
                            <div class="ref-item">
                                <span class="ref-key">{{ key }}</span>: {{ val }}
                            </div>
                        {% endfor %}
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
</body>
</html>
"""

@app.route('/')
def home():
    # Gather clean background logic system parameters
    cpu_percent = psutil.cpu_percent()
    ram_percent = psutil.virtual_memory().percent
    current_platform = sys.platform
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    return render_template_string(
        HTML_TEMPLATE,
        GALAXY_BG=GALAXY_BG,
        PANEL_BG=PANEL_BG,
        ACCENT_CYAN=ACCENT_CYAN,
        ACCENT_PURPLE=ACCENT_PURPLE,
        TEXT_MAIN=TEXT_MAIN,
        TEXT_MUTED=TEXT_MUTED,
        TERM_GREEN=TERM_GREEN,
        cpu=cpu_percent,
        ram=ram_percent,
        platform=current_platform,
        timestamp=now,
        ref_dict=PYTHON_REFERENCE_DICT
    )

if __name__ == '__main__':
    app.run()
