
import streamlit as st
import time
import os
import re

st.set_page_config(
    page_title="Genesis Holodeck",
    page_icon="🦅",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# --- CONFIG ---
REFRESH_RATE = 5 # seconds
ARTIFACTS_DIR = r"C:\Users\P3\.gemini\antigravity\brain\aed627ed-8729-4778-8183-868a3d5fb5d7"
TASK_FILE = os.path.join(ARTIFACTS_DIR, "task.md")
HEALTH_FILE = os.path.join(ARTIFACTS_DIR, "system_health_report.md")

# --- STYLES ---
st.markdown("""
<style>
    .big-font { font-size: 300% !important; font-weight: bold; color: #4F8BF9; }
    .status-box { padding: 20px; border-radius: 10px; background-color: #1E1E1E; border: 1px solid #333; }
    .metric-val { font-size: 24px; font-weight: bold; }
    .metric-label { font-size: 14px; color: #888; }
</style>
""", unsafe_allow_html=True)

# --- HELPERS ---
def read_file(path):
    if not os.path.exists(path): return "File not found."
    with open(path, "r", encoding="utf-8") as f:
        return f.read()

def parse_current_task(task_md):
    # Find the first unchecked task
    lines = task_md.split("\n")
    current_task = "Unknown"
    current_phase = "Unknown"
    
    for line in lines:
        if "- [ ] Task" in line:
            current_phase = line.split("Task")[1].strip()
        if "- [ ]" in line and "Task" not in line:
            current_task = line.replace("- [ ]", "").strip()
            return current_phase, current_task
            
    return "All Tasks Complete", "Maintenance Mode"

def parse_health(health_md):
    status = {}
    if "GHL MCP Status" in health_md:
        ghl_section = health_md.split("## 2. GHL MCP Status")[1].split("##")[0]
        if "🟢" in ghl_section: status["GHL"] = "ONLINE"
        elif "🟡" in ghl_section: status["GHL"] = "CONNECTING"
        else: status["GHL"] = "OFFLINE"
    
    if "Connectivity Matrix" in health_md:
        try:
            # Simple heuristic
            if "🟢" in health_md.split("## 1. Connectivity Matrix")[1]:
                status["INFRA"] = "ONLINE"
            else:
                status["INFRA"] = "WARN"
        except:
            status["INFRA"] = "UNKNOWN"
            
    return status

# --- MAIN UI ---
def main():
    st.markdown('<p class="big-font">GENESIS HOLODECK</p>', unsafe_allow_html=True)
    
    # Refresh logic
    if st.button("Refresh Now"):
        st.rerun()

    col1, col2, col3, col4 = st.columns(4)
    
    # Load Data
    task_content = read_file(TASK_FILE)
    health_content = read_file(HEALTH_FILE)
    
    phase, task = parse_current_task(task_content)
    health = parse_health(health_content)

    # Metrics
    with col1:
        st.markdown(f"""
        <div class="status-box">
            <div class="metric-label">CURRENT PHASE</div>
            <div class="metric-val">{phase}</div>
        </div>
        """, unsafe_allow_html=True)
        
    with col2:
         st.markdown(f"""
        <div class="status-box">
            <div class="metric-label">ACTIVE TASK</div>
            <div class="metric-val">{task[:25]}...</div>
        </div>
        """, unsafe_allow_html=True)

    with col3:
        color = "#00FF00" if health.get("GHL") == "ONLINE" else "#FFA500"
        st.markdown(f"""
        <div class="status-box" style="border-left: 5px solid {color}">
            <div class="metric-label">GHL MCP</div>
            <div class="metric-val">{health.get("GHL", "N/A")}</div>
        </div>
        """, unsafe_allow_html=True)

    with col4:
        st.markdown(f"""
        <div class="status-box">
            <div class="metric-label">SWARM AGENTS</div>
            <div class="metric-val">⚡ ACTIVE</div>
        </div>
        """, unsafe_allow_html=True)

    st.markdown("---")

    # Layout: Task List vs GHL Pipeline vs Logs
    c1, c2, c3 = st.columns([2, 2, 1])
    
    with c1:
        st.subheader("📋 Mission Protocol")
        st.text_area("Task List", task_content, height=400)
    
    with c2:
        st.subheader("🚀 GHL Pipeline")
        st.markdown("""
        | Stage | Count | Value |
        | :--- | :--- | :--- |
        | **New Leads** | 4,886 | $0 |
        | **Pomelli Audit** | 0 | $0 |
        | **Vapi Outreach** | 0 | $0 |
        | **Interested** | 0 | $0 |
        | **Closed** | 0 | $0 |
        """)
        st.info("System Build Mode: Outreach Paused")

        st.subheader("📈 Revenue Mastery (Dual-Track)")
        st.write("**Prong 1: Tradies (Target: $14,850)**")
        st.progress(0)
        st.write("**Prong 2: Creators (Target: $34,800)**")
        st.progress(0)
    
    with c3:
        st.subheader("🏥 System Vitals")
        st.markdown(health_content)
        
        st.subheader("🧠 Swarm Intelligence")
        st.info("Continuous Evolution Loop: RUNNING")
        st.info("Verification Gate 1: ACTIVE (P1 signed)")
        st.success("Big Picture RAG Index: READY")

    # Auto-refresh
    time.sleep(REFRESH_RATE)
    st.rerun()

if __name__ == "__main__":
    main()
