#!/usr/bin/env python3
from pathlib import Path
from datetime import datetime
import json, html, re

W = Path('/Users/ahmad/.openclaw/workspace')
KB = W / 'knowledge_base'
OUTDIR = W / 'apps' / 'mission_control'
OUT = OUTDIR / 'index.html'

SOURCES = [
    ('CEO Report', 'ceo_mission_control_weekly.md', 'execution'),
    ('Daily Tasks', 'goal_aligned_tasks_daily.md', 'execution'),
    ('Email Triage', 'email_triage_daily.md', 'ops'),
    ('P1 Watcher', 'email_p1_watcher_status.md', 'ops'),
    ('Content Factory', 'content_factory_daily.md', 'content'),
    ('Video Pipeline', 'video_idea_pipeline.md', 'content'),
    ('Pain Mining', 'market_pain_mining_daily.md', 'intel'),
    ('X Signals', 'twitter_x_signal_scan.md', 'intel'),
    ('Fathom Meetings', 'fathom_meetings_daily.md', 'intel'),
]


def read(path):
    if not path.exists():
        return ''
    return path.read_text(encoding='utf-8', errors='ignore')


def lines(text):
    out=[]
    for ln in text.splitlines():
        s=ln.strip()
        if not s or s.startswith('#'): continue
        s=s.lstrip('-* ').strip()
        if len(s)<12: continue
        out.append(s)
    return out


def score(line):
    s=line.lower()
    v=0
    for k,w in [('critical',5),('urgent',5),('p1',5),('risk',4),('bottleneck',4),('action',3),('deadline',3),('block',4),('pending',3),('missing',2),('opportunity',3)]:
        if k in s: v+=w
    return v


def top_actions(all_lines, n=6):
    ranked=sorted(all_lines, key=lambda x: score(x), reverse=True)
    dedup=[]
    seen=set()
    for r in ranked:
        k=r.lower()
        if k in seen: continue
        seen.add(k)
        dedup.append(r)
        if len(dedup)>=n: break
    return dedup


def freshness(path):
    if not path.exists(): return ('Missing','bad')
    h=(datetime.now().timestamp()-path.stat().st_mtime)/3600
    if h<8: return (f'{h:.1f}h','good')
    if h<24: return (f'{h:.1f}h','warn')
    return (f'{h:.1f}h','bad')


def main():
    OUTDIR.mkdir(parents=True, exist_ok=True)
    cards=[]
    dataset=[]
    all_lines=[]
    for title,file,cat in SOURCES:
        p=KB/file
        txt=read(p)
        lns=lines(txt)
        all_lines.extend(lns[:8])
        fr,cls=freshness(p)
        preview=lns[:3] if lns else ['No data yet']
        cards.append({'title':title,'file':file,'cat':cat,'fresh':fr,'cls':cls,'preview':preview,'full':txt[:12000] if txt else 'No data yet'})
        dataset.append({'title':title,'file':file,'cat':cat,'fresh':fr,'status':cls,'preview':preview,'full':txt[:12000] if txt else 'No data yet'})

    actions=top_actions(all_lines,6)
    stats={
      'sources':len(SOURCES),
      'available':sum(1 for c in cards if c['full']!='No data yet'),
      'updated':datetime.now().strftime('%Y-%m-%d %H:%M')
    }

    def li(items):
        return ''.join([f"<li>{html.escape(x)}</li>" for x in items])

    cards_html=''.join([f"""
      <article class='card' data-cat='{c['cat']}'>
        <div class='row'><h3>{html.escape(c['title'])}</h3><span class='pill {c['cls']}'>{c['fresh']}</span></div>
        <div class='meta'>{html.escape(c['file'])}</div>
        <ul>{li(c['preview'])}</ul>
        <button onclick=\"openReport('{html.escape(c['title'])}','{html.escape(c['file'])}')\">Open</button>
      </article>
    """ for c in cards])

    html_doc=f"""<!doctype html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width,initial-scale=1'/><title>Mission Control</title>
<style>
:root{{--bg:#0a0d18;--panel:#12172a;--line:#2a3356;--text:#e9eeff;--muted:#9aa9d6;--good:#1f9d55;--warn:#b48a00;--bad:#c53232;}}
*{{box-sizing:border-box}}body{{margin:0;background:var(--bg);color:var(--text);font-family:Inter,-apple-system,Segoe UI,Roboto,sans-serif}}
.wrap{{max-width:1260px;margin:0 auto;padding:20px}}h1{{margin:0 0 4px}}.muted{{color:var(--muted);font-size:13px}}
.top{{display:grid;grid-template-columns:1.4fr 1fr;gap:14px;margin-bottom:14px}}
.panel{{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:14px}}
.kpis{{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}}.k{{background:#0f1426;border:1px solid var(--line);border-radius:10px;padding:10px}}
.n{{font-size:24px;font-weight:700}} .filters{{display:flex;gap:8px;margin:10px 0 12px;flex-wrap:wrap}}
button{{background:#1b2240;border:1px solid #344173;color:#dfe8ff;padding:7px 10px;border-radius:10px;cursor:pointer}}
button.active{{background:#2b3768}}
.grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:10px}}
.card{{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px}}
.row{{display:flex;justify-content:space-between;gap:8px;align-items:center}} h3{{margin:0;font-size:16px}} .meta{{font-size:12px;color:var(--muted);margin:5px 0 8px}}
ul{{margin:0 0 10px 17px;padding:0}}li{{margin:4px 0;line-height:1.25;font-size:13px}}
.pill{{font-size:11px;padding:3px 7px;border-radius:999px}}.good{{background:#123722;color:#b7f5cf}}.warn{{background:#3b2f08;color:#ffe9a3}}.bad{{background:#3d1217;color:#ffc4c4}}
#drawer{{position:fixed;top:0;right:-56%;width:56%;height:100%;background:#0f1426;border-left:1px solid var(--line);padding:16px;transition:.2s;overflow:auto;z-index:20}}
#drawer.open{{right:0}} #overlay{{position:fixed;inset:0;background:rgba(0,0,0,.45);display:none;z-index:10}} #overlay.show{{display:block}}
pre{{white-space:pre-wrap;font-size:12px;line-height:1.35;background:#0a1022;border:1px solid var(--line);border-radius:10px;padding:10px}}
</style></head><body>
<div class='wrap'>
  <h1>Mission Control</h1><div class='muted'>Fast decision cockpit • Updated {stats['updated']}</div>
  <div class='top'>
    <section class='panel'><h3>Priority Feed</h3><ul>{li(actions or ['No priorities detected yet'])}</ul></section>
    <section class='panel'><div class='kpis'>
      <div class='k'><div class='muted'>Sources</div><div class='n'>{stats['sources']}</div></div>
      <div class='k'><div class='muted'>Available</div><div class='n'>{stats['available']}</div></div>
      <div class='k'><div class='muted'>Focus</div><div class='n'>Execute</div></div>
    </div></section>
  </div>
  <div class='filters'>
    <button class='active' onclick="filterCards('all',this)">All</button>
    <button onclick="filterCards('execution',this)">Execution</button>
    <button onclick="filterCards('ops',this)">Ops</button>
    <button onclick="filterCards('content',this)">Content</button>
    <button onclick="filterCards('intel',this)">Intel</button>
  </div>
  <div class='grid'>{cards_html}</div>
</div>
<div id='overlay' onclick='closeDrawer()'></div>
<aside id='drawer'><button onclick='closeDrawer()'>Close</button><h2 id='dtitle'></h2><div class='muted' id='dfile'></div><pre id='dtext'></pre></aside>
<script>
const DATA={json.dumps(dataset)};
function filterCards(cat,btn){{document.querySelectorAll('.filters button').forEach(b=>b.classList.remove('active'));btn.classList.add('active');document.querySelectorAll('.card').forEach(c=>c.style.display=(cat==='all'||c.dataset.cat===cat)?'':'none')}}
function openReport(title,file){{const r=DATA.find(x=>x.title===title&&x.file===file);document.getElementById('dtitle').textContent=title;document.getElementById('dfile').textContent=file;document.getElementById('dtext').textContent=r?r.full:'No data';document.getElementById('drawer').classList.add('open');document.getElementById('overlay').classList.add('show')}}
function closeDrawer(){{document.getElementById('drawer').classList.remove('open');document.getElementById('overlay').classList.remove('show')}}
</script></body></html>"""
    OUT.write_text(html_doc,encoding='utf-8')
    print(str(OUT))

if __name__=='__main__':
    main()
