#!/usr/bin/env python3
from pathlib import Path

# cockpit main.py - add retail router
main = Path("/home/aissa/foodlinkk-command-center/cockpit/app/main.py")
text = main.read_text()
if "retail" not in text:
    text = text.replace(
        "    browser,\n    hermes,\n)",
        "    browser,\n    hermes,\n    retail,\n)",
    )
    text = text.replace(
        "from app.routes import (",
        "from app.routes import (\n    retail,",
    )
if "retail.router," not in text:
    text = text.replace(
        "    marketing.router,\n",
        "    marketing.router,\n    retail.router,\n",
    )
main.write_text(text)

# base.html - add Retail link under Intel
base = Path("/home/aissa/foodlinkk-command-center/cockpit/templates/base.html")
b = base.read_text()
if "/retail" not in b:
    b = b.replace(
        '<a href="/browser"',
        '<a href="/retail" class="{% if request.url.path.startswith(\'/retail\') %}active{% endif %}">Retail</a>\n        <a href="/browser"',
    )
base.write_text(b)

# marketing.html - add Herman tab
m = Path("/home/aissa/foodlinkk-command-center/cockpit/templates/marketing.html")
mt = m.read_text()
if "herman-reco" not in mt:
    mt = mt.replace(
        '<button type="button" :class="{ active: tab===\'analytics\' }" @click="tab=\'analytics\'">Analytics</button>',
        '<button type="button" :class="{ active: tab===\'analytics\' }" @click="tab=\'analytics\'">Analytics</button>\n  <button type="button" :class="{ active: tab===\'herman\' }" @click="tab=\'herman\'">Herman</button>',
    )
    mt += '''
<section class="panel" x-show="tab==='herman'" x-cloak>
  <h2>Herman Recommendations</h2>
  <div id="reco-list">Loading…</div>
  <script>
    fetch('/api/admin/recommendations/pending').then(r=>r.json()).then(d=>{
      const el=document.getElementById('reco-list');
      el.innerHTML=(d.items||[]).map(i=>`<div class="panel" style="margin:.5rem 0"><strong>${i.title}</strong><p>${i.description||''}</p>
        <button class="btn btn-sm btn-approve" onclick="fetch('/api/admin/recommendations/${i.id}/approve',{method:'POST'}).then(()=>location.reload())">Approve</button>
        <button class="btn btn-sm btn-reject" onclick="fetch('/api/admin/recommendations/${i.id}/dismiss',{method:'POST'}).then(()=>location.reload())">Dismiss</button></div>`).join('')||'<p>Geen open recommendations</p>';
    });
  </script>
</section>
'''
    m.write_text(mt)

print("cockpit patched")
