"""
UFM01 Web Monitor for Adafruit Metro ESP32-S2
Creates WiFi Access Point and serves real-time flow data via web interface

Save this as code.py on the CIRCUITPY drive

REQUIRED LIBRARY:
Install adafruit_httpserver library:
1. Download library bundle from: https://circuitpython.org/libraries
2. Extract adafruit_httpserver folder to CIRCUITPY/lib/

Features:
- WiFi Access Point mode
- Real-time web interface with auto-refresh
- Responsive design (mobile-friendly)
- Same styling as Arduino version
"""

import board
import time
import wifi
import socketpool
from adafruit_httpserver import Server, Request, Response
from ufm01_circuitpython import UFM01

# ============================================================================
# CONFIGURATION
# ============================================================================

# WiFi Access Point Settings
WIFI_SSID = "Circuitpython-UFM01"
WIFI_PASSWORD = "12345678"  # Must be 8+ characters
WIFI_CHANNEL = 1

# Web Server Settings
WEB_PORT = 80
WEB_REFRESH_RATE = 2  # seconds

# Sensor Settings
SENSOR_TX_PIN = board.IO5
SENSOR_RX_PIN = board.IO6

# ============================================================================
# INITIALIZE HARDWARE
# ============================================================================

print("\n" + "="*50)
print("UFM01 Web Monitor - CircuitPython")
print("="*50)

# Initialize WiFi Access Point
print("\nInitializing WiFi Access Point...")
print(f"  SSID: {WIFI_SSID}")
print(f"  Password: {WIFI_PASSWORD}")

try:
    wifi.radio.start_ap(
        ssid=WIFI_SSID,
        password=WIFI_PASSWORD,
        channel=WIFI_CHANNEL
    )
    print(f"✓ Access Point created")
    print(f"  IP Address: {wifi.radio.ipv4_address_ap}")
except Exception as e:
    print(f"✗ WiFi AP failed: {e}")
    raise

# Initialize UFM01 sensor
print("\nInitializing UFM01 sensor...")
print(f"  TX: {SENSOR_TX_PIN}")
print(f"  RX: {SENSOR_RX_PIN}")

sensor = UFM01(SENSOR_TX_PIN, SENSOR_RX_PIN)
print("✓ Sensor initialized")

# Initialize HTTP Server
print(f"\nInitializing web server on port {WEB_PORT}...")
pool = socketpool.SocketPool(wifi.radio)
server = Server(pool, "/static", debug=False)

# ============================================================================
# WEB SERVER ROUTES
# ============================================================================

@server.route("/")
def base(request: Request):
    """Main page with sensor data"""

    # Determine if sensor is online
    sensor_online = sensor.is_valid

    # Build HTML response
    html = f"""<!DOCTYPE html>
<html><head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<meta charset='utf-8'>
<meta http-equiv='refresh' content='{WEB_REFRESH_RATE}'>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }}
#main {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; }}
header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px 20px; text-align: center; }}
h1 {{ font-size: 28px; font-weight: 600; margin-bottom: 5px; }}
.subtitle {{ font-size: 14px; opacity: 0.9; }}
.content {{ padding: 30px 20px; }}
.metric-card {{ background: #f8f9fa; border-radius: 10px; padding: 20px; margin-bottom: 15px; border-left: 4px solid #667eea; }}
.metric-label {{ font-size: 12px; color: #6c757d; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }}
.metric-value {{ font-size: 32px; font-weight: 700; color: #2c3e50; margin-bottom: 5px; }}
.metric-unit {{ font-size: 16px; color: #6c757d; font-weight: 400; }}
.status-indicator {{ display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; }}
.status-online {{ background: #28a745; }}
.status-offline {{ background: #dc3545; }}
.button {{ display: block; width: 100%; padding: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; text-decoration: none; text-align: center; margin-top: 20px; transition: transform 0.2s, box-shadow 0.2s; }}
.button:hover {{ transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.4); }}
.button:active {{ transform: translateY(0); }}
.footer {{ text-align: center; padding: 15px; font-size: 12px; color: #6c757d; border-top: 1px solid #e9ecef; }}
.info-box {{ background: #e7f3ff; border-left: 4px solid #2196F3; padding: 15px; margin-top: 15px; border-radius: 5px; }}
.info-box p {{ font-size: 13px; color: #1976D2; margin: 5px 0; }}
@media (max-width: 480px) {{
  .metric-value {{ font-size: 24px; }}
  h1 {{ font-size: 24px; }}
}}
</style>
<title>UFM01 Monitor</title>
</head><body>
<div id='main'>
<header>
<h1>UFM01 Flow Monitor</h1>
<p class='subtitle'>CircuitPython Edition</p>
</header>
<div class='content'>"""

    # Accumulated Flow Card
    html += "<div class='metric-card'>"
    html += "<div class='metric-label'>"
    html += f"<span class='status-indicator {'status-online' if sensor_online else 'status-offline'}'></span>"
    html += "Accumulated Flow"
    if not sensor_online:
        html += " (Offline)"
    html += "</div>"
    html += "<div class='metric-value'>"
    html += f"{sensor.accumulated_flow:.2f}" if sensor_online else "---"
    html += "</div>"
    html += "<div class='metric-unit'>Liters</div>"
    html += "</div>"

    # Instantaneous Flow Card
    html += "<div class='metric-card'>"
    html += "<div class='metric-label'>"
    html += f"<span class='status-indicator {'status-online' if sensor_online else 'status-offline'}'></span>"
    html += "Instantaneous Flow Rate"
    if not sensor_online:
        html += " (Offline)"
    html += "</div>"
    html += "<div class='metric-value'>"
    html += f"{sensor.instantaneous_flow:.1f}" if sensor_online else "---"
    html += "</div>"
    html += "<div class='metric-unit'>Liters/hour</div>"
    html += "</div>"

    # Temperature Card
    html += "<div class='metric-card'>"
    html += "<div class='metric-label'>Temperature</div>"
    html += "<div class='metric-value'>"
    html += f"{sensor.temperature:.1f}" if sensor_online else "---"
    html += "</div>"
    html += "<div class='metric-unit'>°Celsius</div>"
    html += "</div>"

    # Peak Flow Card
    html += "<div class='metric-card'>"
    html += "<div class='metric-label'>Peak Flow Rate</div>"
    html += "<div class='metric-value'>"
    html += f"{sensor.max_flow_rate:.1f}"
    html += "</div>"
    html += "<div class='metric-unit'>Liters/hour</div>"
    html += "</div>"

    # Statistics Info Box
    html += "<div class='info-box'>"
    html += f"<p><strong>Statistics:</strong></p>"
    html += f"<p>Frames Received: {sensor.stats['frames_received']}</p>"
    html += f"<p>Parse Errors: {sensor.stats['parse_errors']}</p>"
    if sensor.stats['last_frame_time'] > 0:
        elapsed = time.monotonic() - sensor.stats['last_frame_time']
        html += f"<p>Last Update: {elapsed:.1f}s ago</p>"
    html += "</div>"

    # Reset Button
    html += "<a href='/reset' class='button'>Reset Accumulated Flow</a>"

    html += "</div>"
    html += f"<div class='footer'>Auto-refresh every {WEB_REFRESH_RATE} seconds | Powered by CircuitPython</div>"
    html += "</div></body></html>"

    return Response(request, html, content_type="text/html")


@server.route("/reset")
def reset_flow(request: Request):
    """Reset accumulated flow and redirect back to main page"""
    print("🔄 Reset button pressed - clearing accumulated flow")

    success = sensor.clear_accumulated_flow()
    if success:
        print(" ✓ Accumulated flow cleared successfully")
        message = "Reset OK"
    else:
        print(" ✗ Failed to clear accumulated flow")
        message = "Reset failed"

    # Robust redirect: 302 + Location header + meta refresh + JS
    html = f"""<!DOCTYPE html>
<html><head>
<meta charset='utf-8'>
<title>Redirecting…</title>
<meta http-equiv='refresh' content='0; url=/' />
<script>location.replace('/');</script>
<style>body{{font-family:Arial,sans-serif}} .msg{{margin:2rem}}</style>
</head><body>
<div class='msg'>{message}. Returning to main page… <a href='/'>Continue</a></div>
</body></html>
"""
    return Response(
        request,
        html,
        content_type="text/html",
        headers={"Location": "/"},
        status=(302, "Found"),
    )


# ============================================================================
# START SERVER AND MAIN LOOP
# ============================================================================

print("✓ Web server initialized")
print("\n" + "="*50)
print("System Ready!")
print("="*50)
print(f"\nConnect to WiFi: {WIFI_SSID}")
print(f"Visit: http://{wifi.radio.ipv4_address_ap}")
print("\nMonitoring sensor data...\n")

# Start the server
server.start(str(wifi.radio.ipv4_address_ap), port=WEB_PORT)

# Main loop
last_sensor_print = time.monotonic()

while True:
    # Update sensor data
    if sensor.update():
        # Print to console occasionally
        if time.monotonic() - last_sensor_print > 5:
            print(f"📊 Flow: {sensor.instantaneous_flow:.1f} L/h | "
                  f"Total: {sensor.accumulated_flow:.2f} L | "
                  f"Temp: {sensor.temperature:.1f}°C")
            last_sensor_print = time.monotonic()

    # Poll the server (handles incoming requests)
    try:
        server.poll()
    except Exception as e:
        print(f"Server error: {e}")
        time.sleep(0.1)

    # Small delay to prevent CPU hogging
    time.sleep(0.001)