from flask import Flask, jsonify, render_template_string
import subprocess

app = Flask(__name__)

PROJECTS = [
    {'id': 'leads', 'name': 'Lead Engine', 'desc': 'B2B Lead Enrichment & Dashboard. Kampagnen-Verwaltung.', 'icon': '🎯', 'url': 'https://leads.agentsolutions-mallorca.com', 'status_type': 'docker', 'container': 'lead-engine'},
    # Die beiden Marken-Zweige werden im Dashboard strikt getrennt dargestellt.
    # Der alte V2-Generator bleibt technisch bestehen, erscheint aber nicht mehr als
    # eigenstaendiger "Social Media Agent", damit keine Markenverwechslung entsteht.
    {'id': 'sma-mas', 'name': 'Social Media Agent – MAS', 'desc': 'Mallorca Air Services / Lüftungsprofi. Radar, Content Queue und Publishing für Lüftung, Feuchte und Immobilien.', 'icon': '📡', 'url': 'https://sma-mas.agentsolutions-mallorca.com/cockpit?days=1&sort=op_priority&tab=radar', 'status_type': 'systemd', 'service': 'sma-core-api.service', 'group': 'sma'},
    {'id': 'sma-asol', 'name': 'Social Media Agent – ASOL', 'desc': 'Agent Solutions. KI-Unternehmensberatung, individuelle Speziallösungen, Automatisierung und Agents.', 'icon': '🧠', 'url': 'https://sma-asol.agentsolutions-mallorca.com', 'status_type': 'static', 'status_value': 'preview', 'group': 'sma'},
    {'id': 'telefon', 'name': 'Telefon Agent', 'desc': 'Twilio IVR + KI-Sprachassistent fuer eingehende Anrufe.', 'icon': '☎', 'url': 'https://telefon.agentsolutions-mallorca.com', 'status_type': 'static', 'status_value': 'in Entwicklung'},
    {'id': 'vento', 'name': 'Vento', 'desc': 'WhatsApp-Empfangsassistent. Erkennt Kunden, führt Erstgespräch, bereitet Rückruf vor.', 'icon': '💬', 'url': 'https://vento.agentsolutions-mallorca.com/docs', 'status_type': 'docker', 'container': 'vento', 'db_url': 'https://vento.agentsolutions-mallorca.com/customers'},
    {'id': 'youtube', 'name': 'YouTube Research', 'desc': 'Video-Datenbank & KI-Analyse. Transkripte, Skills, Filter.', 'icon': '📊', 'url': 'https://youtube.agentsolutions-mallorca.com', 'status_type': 'systemd', 'service': 'youtube-research.service'},
    {'id': 'youtube-lm', 'name': 'YouTube LM', 'desc': 'Verifizierte Wissensaufbereitung, Lernstruktur und Audio-Skripte aus YouTube-Videos.', 'icon': '🎧', 'url': 'https://youtube.agentsolutions-mallorca.com/youtube-lm', 'status_type': 'systemd', 'service': 'youtube-research.service'},
    {'id': 'content-extraction', 'name': 'YouTube Extraction', 'desc': 'Inhalte extrahieren, bewerten, filtern und priorisieren. (geschuetzt, Basic Auth)', 'icon': '🗂️', 'url': 'https://content-extraction.agentsolutions-mallorca.com', 'status_type': 'systemd', 'service': 'content-extraction.service'},
    {'id': 'donna', 'name': 'Donna', 'desc': 'Lokale Windows-Assistentin (Electron). Aktueller Release: 1.1.2-free-models.', 'icon': '🗂️', 'url': 'https://agentsolutions-mallorca.com/downloads/donna/', 'location': 'local', 'status_type': 'static', 'status_value': 'lokal'},
    {'id': 'solar', 'name': 'Solar-Wirtschaftlichkeits-App', 'desc': 'Photovoltaik, Eigenverbrauch, Förderung und Amortisation berechnen.', 'icon': '☀️', 'url': 'https://solar.agentsolutions-mallorca.com', 'vip_url': 'https://solar.agentsolutions-mallorca.com/admin/vip', 'status_type': 'systemd', 'service': 'solar-wirtschaftlichkeit.service'},
]

def get_status(project):
    status_type = project.get('status_type')

    if status_type == 'static':
        return project.get('status_value', 'pending')

    if status_type == 'docker':
        container = project.get('container')
        try:
            result = subprocess.run(
                ['docker', 'inspect', '--format', '{{.State.Status}}', container],
                capture_output=True,
                text=True,
                timeout=5
            )
            state = result.stdout.strip()
            return 'online' if state == 'running' else 'offline'
        except Exception:
            return 'offline'

    if status_type == 'systemd':
        service = project.get('service')
        try:
            result = subprocess.run(
                ['systemctl', 'is-active', service],
                capture_output=True,
                text=True,
                timeout=5
            )
            return 'online' if result.stdout.strip() == 'active' else 'offline'
        except Exception:
            return 'offline'

    return 'pending'

HTML = """<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Projects</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #0f1117; color: #e2e8f0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; min-height: 100vh; }
header { padding: 2rem 3rem; border-bottom: 1px solid #1e2330; display: flex; justify-content: space-between; align-items: center; }
header h1 { font-size: 1.5rem; font-weight: 600; color: #fff; }
header span { font-size: 0.85rem; color: #64748b; }
header a { font-size: 0.8rem; color: #3b82f6; text-decoration: none; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1.5rem; padding: 3rem; }
.card { background: #161b27; border: 1px solid #1e2330; border-radius: 12px; padding: 1.5rem; }
.card-header { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 1rem; }
.card-icon { font-size: 2rem; }
.badge { font-size: 0.7rem; padding: 0.25rem 0.7rem; border-radius: 99px; font-weight: 600; }
.badge.online { background: #1a3a2a; color: #4ade80; border: 1px solid #166534; }
.badge.offline { background: #3a1a1a; color: #f87171; border: 1px solid #7f1d1d; }
.badge.pending { background: #2a2a2a; color: #94a3b8; border: 1px solid #334155; }
.badge.lokal { background: #1e2a3a; color: #818cf8; border: 1px solid #3730a3; }
.badge.preview { background: #2a2440; color: #c4b5fd; border: 1px solid #6d28d9; }
.section-title { font-size: 0.85rem; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 1.5px; padding: 0 3rem; margin-top: 1.5rem; }
.card-title { font-size: 1.1rem; font-weight: 600; color: #fff; margin-bottom: 0.4rem; }
.card-desc { font-size: 0.85rem; color: #64748b; line-height: 1.5; margin-bottom: 1.2rem; }
.card-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.btn { font-size: 0.75rem; padding: 0.4rem 0.9rem; border-radius: 6px; border: none; cursor: pointer; font-weight: 500; }
.btn-open { background: #1e3a5f; color: #60a5fa; }
.btn-restart { background: #1e3a2a; color: #4ade80; }
.btn-stop { background: #3a1e1e; color: #f87171; }
.btn-start { background: #1a3a2a; color: #4ade80; }
footer { text-align: center; padding: 2rem; color: #334155; font-size: 0.8rem; }
</style></head><body>
<header><div><h1>Projects</h1><span>Projekt-Dashboard VPS</span></div>
<a href="https://agentsolutions-mallorca.com" style="font-size:0.85rem;color:#3b82f6;text-decoration:none;border:1px solid #1e3a5f;padding:0.4rem 1rem;border-radius:8px;">&#8592; Agent Solutions</a></header>
<div class="section-title">Social Media Agents</div>
<div class="grid" id="grid-sma">
{% for p in projects %}{% if p.group == 'sma' %}
<div class="card" id="card-{{p.id}}">
<div class="card-header"><div class="card-icon">{{p.icon}}</div>
<span class="badge pending" id="badge-{{p.id}}">...</span></div>
<div class="card-title">{{p.name}}</div>
<div class="card-desc">{{p.desc}}</div>
<div class="card-actions">
{% if p.url %}<button class="btn btn-open" onclick='openProjectWindow({{ p.url|tojson }})'>&#214;ffnen</button>{% endif %}
</div></div>
{% endif %}{% endfor %}
</div>
<div class="section-title">Weitere VPS-Projekte</div>
<div class="grid" id="grid">
{% for p in projects %}{% if p.location != 'local' and p.group != 'sma' %}
<div class="card" id="card-{{p.id}}">
<div class="card-header"><div class="card-icon">{{p.icon}}</div>
<span class="badge pending" id="badge-{{p.id}}">...</span></div>
<div class="card-title">{{p.name}}</div>
<div class="card-desc">{{p.desc}}</div>
<div class="card-actions">
{% if p.url %}<button class="btn btn-open" onclick='openProjectWindow({{ p.url|tojson }})'>&#214;ffnen</button>{% endif %}{% if p.vip_url %}<button class="btn" style="background:#2a2440;color:#c4b5fd" onclick='openProjectWindow({{ p.vip_url|tojson }})'>VIP-Zugänge</button>{% endif %}{% if p.db_url %}<button class="btn" style="background:#1e2a3a;color:#818cf8" onclick='openProjectWindow({{ p.db_url|tojson }})'>Kunden DB</button>{% endif %}
</div></div>
{% endif %}{% endfor %}
</div>
<div class="section-title">Lokale Projekte</div>
<div class="grid" id="grid-local">
{% for p in projects %}{% if p.location == 'local' %}
<div class="card" id="card-{{p.id}}">
<div class="card-header"><div class="card-icon">{{p.icon}}</div>
<span class="badge lokal" id="badge-{{p.id}}">lokal</span></div>
<div class="card-title">{{p.name}}</div>
<div class="card-desc">{{p.desc}}</div>
<div class="card-actions">
{% if p.url %}<a href="{{p.url}}" target="_blank"><button class="btn btn-open">&#214;ffnen</button></a>{% endif %}
</div></div>
{% endif %}{% endfor %}
</div>
<footer>Agent Solutions Projects VPS IONOS 31.70.68.228</footer>
<script>
function openProjectWindow(url) {
  window.open(
    url,
    "_blank",
    "width=1400,height=900,resizable=yes,scrollbars=yes,noopener"
  );
}

function updateStatus() {
  fetch("/api/status").then(r=>r.json()).then(data => {
    data.forEach(s => {
      const b = document.getElementById("badge-"+s.id);
      b.textContent = s.status;
      const cls =
        s.status === "online" ? "online" :
        s.status === "offline" ? "offline" :
        s.status === "lokal" ? "lokal" :
        s.status === "preview" ? "preview" :
        "pending";
      b.className = "badge " + cls;
    });
  });
}
updateStatus();
setInterval(updateStatus, 15000);
</script></body></html>"""

@app.route('/')
def index():
    return render_template_string(HTML, projects=PROJECTS)

@app.route('/api/status')
def status():
    return jsonify([{'id': p['id'], 'status': get_status(p)} for p in PROJECTS])

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5001, debug=False)
