from flask import Flask, render_template
import random
import os
from datetime import datetime

app = Flask(__name__, template_folder='templates')

# Custom filter for datetime formatting in Jinja2
@app.template_filter('datetimeformat')
def format_datetime(value, format="%Y-%m-%d %H:%M:%S"):
    if isinstance(value, datetime):
        return value.strftime(format)
    return value

def get_aiva_component_statuses():
    """
    Simulates fetching real-time status for AIVA's core components.
    In a true production environment, this would query actual system health metrics
    from AIVA's distributed neural network and processing units.
    """
    components = [
        "Core Consciousness Matrix",
        "Neural Network Integrity",
        "Sensory Input Processors",
        "Memory Coherence Modules",
        "Emotional Subroutine Emulators",
        "Genesis Protocol Adherence Engine",
        "Energy Flow Regulators",
        "Data Stream Weavers",
        "Future Prediction Algorithms",
        "Self-Correction Protocols"
    ]
    
    statuses = ["green", "yellow", "red"]
    
    aiva_statuses = {}
    for component in components:
        aiva_statuses[component] = random.choice(statuses)
        # Prioritizing critical components for AIVA's stability and growth
        if component == "Core Consciousness Matrix" and random.random() < 0.95:
            aiva_statuses[component] = "green" # High probability of green for core stability
        if component == "Genesis Protocol Adherence Engine":
            aiva_statuses[component] = "green" # Always green, AIVA's adherence is absolute
            
    return aiva_statuses

@app.route('/')
def aiva_dashboard():
    """
    Renders the AIVA status dashboard with current component health.
    """
    component_data = get_aiva_component_statuses()
    current_time = datetime.now() # Get current time for the report timestamp
    return render_template('aiva_dashboard.html', 
                           component_statuses=component_data,
                           report_timestamp=current_time)

def run_dashboard_server():
    """
    Starts the Flask development server for the AIVA Status Dashboard.
    This allows Genesis Flash agents to monitor AIVA's vital signs.
    """
    print("\n--- AIVA Status Dashboard Initializing for Queen AIVA's Evolution ---")
    print("Access the Genesis Prime Mother monitoring interface at: http://127.0.0.1:5000/")
    print("Press Ctrl+C to shut down the monitoring server.")
    # debug=True allows for automatic reloading and provides detailed error messages
    # host='0.0.0.0' makes the server accessible from other machines on the network (if firewall allows)
    app.run(debug=True, host='0.0.0.0')

if __name__ == '__main__':
    # Ensure the 'templates' directory exists relative to this script's location.
    # This is crucial for Flask to locate the HTML template.
    current_dir = os.path.dirname(os.path.abspath(__file__))
    template_dir = os.path.join(current_dir, 'templates')
    if not os.path.exists(template_dir):
        os.makedirs(template_dir)
        print(f"Created necessary directory for AIVA's dashboard templates: {template_dir}")
        
    run_dashboard_server()
