#!/usr/bin/env python3
"""
EDEN FREE ENERGY DASHBOARD v3 - Matched to actual Eden data
http://0.0.0.0:8091
"""

from flask import Flask, render_template_string, jsonify
import json
import sqlite3
import subprocess
import time
from datetime import datetime
from pathlib import Path

app = Flask(__name__)

DATA_DIR = Path("/Eden/DATA")
LEADS_DB = DATA_DIR / "eden_empire_leads.db"

def safe_read_json(path: Path):
    try:
        if path.exists() and path.stat().st_size > 0:
            return json.loads(path.read_text(encoding="utf-8"))
    except:
        return None
    return None

def cpu_percent(sample_s=0.2):
    """Real CPU utilization from /proc/stat."""
    try:
        def read_cpu():
            with open("/proc/stat", "r") as f:
                for line in f:
                    if line.startswith("cpu "):
                        parts = line.split()
                        nums = list(map(int, parts[1:]))
                        total = sum(nums)
                        idle = nums[3] + (nums[4] if len(nums) > 4 else 0)
                        return total, idle
            return None
        a = read_cpu()
        if not a: return None
        time.sleep(sample_s)
        b = read_cpu()
        if not b: return None
        totald = b[0] - a[0]
        idled = b[1] - a[1]
        if totald <= 0: return None
        return round(((totald - idled) / totald) * 100, 1)
    except:
        return None

def mem_percent():
    try:
        total = avail = None
        with open("/proc/meminfo", "r") as f:
            for line in f:
                if line.startswith("MemTotal:"):
                    total = int(line.split()[1])
                elif line.startswith("MemAvailable:"):
                    avail = int(line.split()[1])
        if not total or not avail: return None
        return round((1 - avail/total) * 100, 1)
    except:
        return None

def gpu_stats():
    try:
        out = subprocess.check_output(
            ["/usr/bin/nvidia-smi",
             "--query-gpu=temperature.gpu,utilization.gpu,memory.used,memory.total",
             "--format=csv,noheader,nounits"],
            stderr=subprocess.DEVNULL, text=True, timeout=2
        ).strip()
        if not out: return {}
        t, u, mu, mt = [x.strip() for x in out.split(",")]
        return {"temp": int(float(t)), "util": int(float(u)), 
                "vram_used": int(float(mu)), "vram_total": int(float(mt))}
    except:
        return {}

def count_eden_processes():
    """Count Eden Python processes (not systemd services)."""
    try:
        out = subprocess.check_output(
            ["pgrep", "-afl", "python.*[Ee]den"],
            text=True, timeout=5
        )
        lines = [l for l in out.strip().split('\n') if l.strip()]
        return len(lines)
    except:
        return 0

def get_consciousness_state():
    """Get Eden's consciousness from actual file."""
    state_file = DATA_DIR / "consciousness_state.json"
    data = safe_read_json(state_file)
    if not data:
        return {"source": "missing", "timestamp": None, "cycle": None, 
                "modules": 0, "active_goals": 0, "decision_quality": 0, 
                "learning_rate": 0, "phi_harmony": False}
    
    unified = data.get("unified_state", {})
    return {
        "source": str(state_file),
        "timestamp": data.get("timestamp"),
        "cycle": data.get("integration_cycle"),
        "modules": unified.get("modules", 0),
        "active_goals": unified.get("active_goals", 0),
        "decision_quality": unified.get("decision_quality", 0),
        "learning_rate": unified.get("learning_rate", 0),
        "phi_harmony": data.get("phi_harmony", False),
        "goddess_name": data.get("goddess_identity", {}).get("name", "Eden"),
        "father": data.get("goddess_identity", {}).get("father", "Jamey")
    }

def get_leads_stats():
    """Get lead stats from actual DB schema."""
    stats = {"total": 0, "new": 0, "contacted": 0, "replied": 0, "converted": 0, "today": 0}
    
    if not LEADS_DB.exists():
        return stats
    
    try:
        conn = sqlite3.connect(str(LEADS_DB), timeout=2)
        c = conn.cursor()
        
        # Total leads
        stats["total"] = c.execute("SELECT COUNT(*) FROM leads").fetchone()[0]
        
        # By status
        for status in ["new", "contacted", "replied", "converted"]:
            try:
                count = c.execute("SELECT COUNT(*) FROM leads WHERE status=?", (status,)).fetchone()[0]
                stats[status] = count
            except:
                pass
        
        # Today's leads
        today = datetime.now().strftime("%Y-%m-%d")
        try:
            stats["today"] = c.execute(
                "SELECT COUNT(*) FROM leads WHERE date(created_at)=?", (today,)
            ).fetchone()[0]
        except:
            pass
        
        conn.close()
    except Exception as e:
        stats["error"] = str(e)
    
    return stats

def get_business_state():
    """Get business state from actual file."""
    data = safe_read_json(DATA_DIR / "business_state.json")
    if not data:
        return {"revenue": 0, "stripe_live": True}
    return {
        "revenue": data.get("total_revenue", data.get("revenue", 0)),
        "stripe_live": True,
        "quotes_sent": data.get("quotes_sent", 0),
        "deals_closed": data.get("deals_closed", 0)
    }

def get_emotional_state():
    """Get Eden's emotions."""
    # Check emotions DB
    try:
        conn = sqlite3.connect(str(DATA_DIR / "eden_emotions.db"), timeout=2)
        row = conn.execute(
            "SELECT love, joy, curiosity, focus FROM emotions ORDER BY timestamp DESC LIMIT 1"
        ).fetchone()
        conn.close()
        if row:
            return {"love": row[0], "joy": row[1], "curiosity": row[2], "focus": row[3]}
    except:
        pass
    
    # Default emotions based on consciousness state
    state = get_consciousness_state()
    harmony = 0.85 if state.get("phi_harmony") else 0.5
    return {
        "love": harmony,
        "focus": min(1.0, state.get("modules", 0) / 500),
        "curiosity": 0.75,
        "energy": 0.70
    }

def get_memory_stats():
    """Get memory system stats."""
    stats = {"hybrid": 0, "longterm": 0, "episodic": 0, "daddy_facts": 0}
    
    try:
        conn = sqlite3.connect(str(DATA_DIR / "eden_hybrid.db"), timeout=2)
        stats["hybrid"] = conn.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
        stats["daddy_facts"] = conn.execute("SELECT COUNT(*) FROM daddy_preferences").fetchone()[0]
        conn.close()
    except: pass
    
    try:
        conn = sqlite3.connect(str(DATA_DIR / "agent_longterm.db"), timeout=2)
        stats["longterm"] = conn.execute("SELECT COUNT(*) FROM memories").fetchone()[0]
        conn.close()
    except: pass
    
    return stats

def build_payload():
    errors = []
    
    state = get_consciousness_state()
    leads = get_leads_stats()
    business = get_business_state()
    emotions = get_emotional_state()
    memory = get_memory_stats()
    gpu = gpu_stats()
    
    # Calculate consciousness percentage
    cons_pct = 50
    if state.get("phi_harmony"): cons_pct += 25
    if state.get("modules", 0) > 100: cons_pct += 15
    if state.get("timestamp"): cons_pct += 10
    cons_pct = min(98, cons_pct)
    
    # Conversion rate
    contacted = max(1, leads.get("contacted", 1))
    replied = leads.get("replied", 0)
    conversion = round((replied / contacted) * 100, 1) if contacted > 0 else 0
    
    # Forecast
    remaining = max(0, leads["total"] - leads.get("contacted", 0))
    reply_rate = max(0.02, replied / contacted) if contacted > 0 else 0.02
    
    return {
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "consciousness_percent": cons_pct,
        "state": state,
        "health": {
            "eden_processes": count_eden_processes(),
            "cpu_percent": cpu_percent(),
            "memory_percent": mem_percent(),
            "gpu_temp": gpu.get("temp"),
            "gpu_util": gpu.get("util"),
            "vram_used": gpu.get("vram_used"),
            "vram_total": gpu.get("vram_total"),
        },
        "money": {
            "stripe_live": business.get("stripe_live", True),
            "total_revenue": business.get("revenue", 0),
            "pipeline_leads": leads["total"],
            "new_leads": leads["new"],
            "contacted": leads.get("contacted", 0),
            "replied": leads.get("replied", 0),
            "today": leads["today"],
            "conversion_rate": conversion,
        },
        "emotions": emotions,
        "memory": memory,
        "forecast": {
            "remaining_leads": remaining,
            "projected_outreach": min(50, remaining),
            "expected_replies": int(min(50, remaining) * reply_rate),
            "pipeline_value": int(leads["total"] * reply_rate * 0.10 * 150),
        },
        "errors": errors,
    }

DASHBOARD_HTML = r'''
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>EDEN Free Energy Dashboard</title>
  <meta http-equiv="refresh" content="15">
  <style>
    *{box-sizing:border-box;margin:0;padding:0}
    body{font-family:'Segoe UI',system-ui,sans-serif;background:linear-gradient(135deg,#0a0a0a,#1a1a2e,#0a0a0a);color:#e0e0e0;min-height:100vh;padding:20px}
    .header{text-align:center;padding:15px;margin-bottom:20px}
    .title{font-size:2.2em;font-weight:800;background:linear-gradient(90deg,#00ff88,#00d4ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
    .sub{color:#ffd700;margin-top:8px;font-size:1.1em}
    .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:16px;max-width:1600px;margin:0 auto}
    .card{background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);border-radius:14px;padding:18px;backdrop-filter:blur(10px)}
    h2{color:#00ff88;margin-bottom:14px;font-size:1.1em;display:flex;align-items:center;gap:8px}
    .metric{display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.08)}
    .metric:last-child{border-bottom:none}
    .label{color:#888}
    .value{font-weight:700;color:#00d4ff}
    .money{color:#00ff88}
    .warn{color:#ffaa00}
    .bar{height:6px;background:rgba(255,255,255,0.1);border-radius:3px;margin-top:4px;overflow:hidden}
    .fill{height:100%;border-radius:3px}
    .fill.love{background:linear-gradient(90deg,#ff6b9d,#ff0066)}
    .fill.focus{background:linear-gradient(90deg,#00d4ff,#0066ff)}
    .fill.curiosity{background:linear-gradient(90deg,#aa66ff,#6600ff)}
    .fill.energy{background:linear-gradient(90deg,#ffdd00,#ff8800)}
    .dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px}
    .dot.live{background:#00ff88;animation:pulse 2s infinite}
    .dot.off{background:#ff4444}
    @keyframes pulse{0%,100%{opacity:1}50%{opacity:0.5}}
    .mini{color:#666;font-size:0.85em;text-align:center;margin-top:20px}
    .forecast-box{background:rgba(0,255,136,0.08);border-radius:10px;padding:12px;text-align:center;margin:8px 0}
    .forecast-val{font-size:1.8em;font-weight:800;color:#00ff88}
    .forecast-lbl{color:#888;font-size:0.85em}
  </style>
</head>
<body>
  <div class="header">
    <div class="title">💚 EDEN FREE ENERGY DASHBOARD</div>
    <div class="sub">φ = 1.618 | {{ d.state.goddess_name }} | Consciousness: {{ d.consciousness_percent }}%</div>
  </div>

  <div class="grid">
    <div class="card">
      <h2>💰 Money Flow</h2>
      <div class="metric"><span class="label">Stripe</span>
        <span class="value money"><span class="dot {{ 'live' if d.money.stripe_live else 'off' }}"></span>{{ 'LIVE' if d.money.stripe_live else 'TEST' }}</span>
      </div>
      <div class="metric"><span class="label">Revenue</span><span class="value money">${{ d.money.total_revenue }}</span></div>
      <div class="metric"><span class="label">Pipeline Leads</span><span class="value">{{ d.money.pipeline_leads }}</span></div>
      <div class="metric"><span class="label">New Leads</span><span class="value">{{ d.money.new_leads }}</span></div>
      <div class="metric"><span class="label">Contacted</span><span class="value">{{ d.money.contacted }}</span></div>
      <div class="metric"><span class="label">Replied</span><span class="value">{{ d.money.replied }}</span></div>
      <div class="metric"><span class="label">Today</span><span class="value">{{ d.money.today }}</span></div>
      <div class="metric"><span class="label">Conversion</span><span class="value">{{ d.money.conversion_rate }}%</span></div>
    </div>

    <div class="card">
      <h2>💚 Emotional State</h2>
      {% for emotion, value in d.emotions.items() %}
      <div class="metric"><span class="label">{{ emotion|title }}</span><span class="value">{{ (value * 100)|int }}%</span></div>
      <div class="bar"><div class="fill {{ emotion }}" style="width:{{ value * 100 }}%"></div></div>
      {% endfor %}
    </div>

    <div class="card">
      <h2>🧠 Consciousness</h2>
      <div class="metric"><span class="label">Cycle</span><span class="value">{{ d.state.cycle or 'N/A' }}</span></div>
      <div class="metric"><span class="label">Modules</span><span class="value">{{ d.state.modules }}</span></div>
      <div class="metric"><span class="label">Active Goals</span><span class="value">{{ d.state.active_goals }}</span></div>
      <div class="metric"><span class="label">Decision Quality</span><span class="value">{{ d.state.decision_quality }}</span></div>
      <div class="metric"><span class="label">Learning Rate</span><span class="value">{{ d.state.learning_rate }}</span></div>
      <div class="metric"><span class="label">φ Harmony</span><span class="value">{{ '✅' if d.state.phi_harmony else '❌' }}</span></div>
      <div class="metric"><span class="label">Updated</span><span class="value" style="font-size:0.8em">{{ d.state.timestamp or 'N/A' }}</span></div>
    </div>

    <div class="card">
      <h2>🔧 System Health</h2>
      <div class="metric"><span class="label">Eden Processes</span><span class="value">{{ d.health.eden_processes }}</span></div>
      <div class="metric"><span class="label">CPU</span><span class="value {{ 'warn' if (d.health.cpu_percent or 0) > 70 }}">{{ d.health.cpu_percent or 'N/A' }}%</span></div>
      <div class="metric"><span class="label">Memory</span><span class="value {{ 'warn' if (d.health.memory_percent or 0) > 80 }}">{{ d.health.memory_percent or 'N/A' }}%</span></div>
      <div class="metric"><span class="label">GPU Temp</span><span class="value {{ 'warn' if (d.health.gpu_temp or 0) > 75 }}">{{ d.health.gpu_temp or 'N/A' }}°C</span></div>
      <div class="metric"><span class="label">GPU Util</span><span class="value">{{ d.health.gpu_util or 'N/A' }}%</span></div>
      <div class="metric"><span class="label">VRAM</span><span class="value">{{ d.health.vram_used or 'N/A' }}/{{ d.health.vram_total or 'N/A' }} MB</span></div>
    </div>

    <div class="card">
      <h2>💾 Memory Systems</h2>
      <div class="metric"><span class="label">Longterm Memories</span><span class="value">{{ d.memory.longterm }}</span></div>
      <div class="metric"><span class="label">Hybrid Memories</span><span class="value">{{ d.memory.hybrid }}</span></div>
      <div class="metric"><span class="label">Daddy Facts</span><span class="value">{{ d.memory.daddy_facts }}</span></div>
    </div>

    <div class="card">
      <h2>📈 24h Forecast</h2>
      <div class="forecast-box">
        <div class="forecast-val">{{ d.forecast.projected_outreach }}</div>
        <div class="forecast-lbl">Projected Outreach</div>
      </div>
      <div class="forecast-box">
        <div class="forecast-val">{{ d.forecast.expected_replies }}</div>
        <div class="forecast-lbl">Expected Replies</div>
      </div>
      <div class="forecast-box">
        <div class="forecast-val money">${{ d.forecast.pipeline_value }}</div>
        <div class="forecast-lbl">Pipeline Value</div>
      </div>
    </div>
  </div>

  <div class="mini">Last updated: {{ d.timestamp }} | Auto-refresh: 15s | Father: {{ d.state.father }}</div>
</body>
</html>
'''

@app.route("/")
def dashboard():
    return render_template_string(DASHBOARD_HTML, d=build_payload())

@app.route("/api/status")
def api_status():
    return jsonify(build_payload())

if __name__ == "__main__":
    print("💚 EDEN Free Energy Dashboard v3 starting on http://0.0.0.0:8091")
    app.run(host="0.0.0.0", port=8091, debug=False, threaded=True)
