from pathlib import Path
p=Path('/opt/struktur/content-extraction/templates/index.html')
s=p.read_text()
s=s.replace(''' .quality-broad { background: #fef3c7; color: #92400e; }\n''',''' .quality-broad { background: #fef3c7; color: #92400e; }\n .analysis-badge { display:inline-flex; align-items:center; border-radius:999px; padding:4px 8px; font-size:12px; font-weight:700; margin-left:6px; }\n .analysis-done { background:#e0f2fe; color:#075985; border:1px solid #bae6fd; }\n .analysis-missing { background:#fee2e2; color:#991b1b; border:1px solid #fecaca; }\n''',1)
anchor=''' <label for="limit" class="small" style="color:#334155; font-weight:600; margin-left:8px;">Anzeige:</label>\n'''
insert=''' <label style="display:inline-flex;align-items:center;gap:6px;font-size:13px;color:#334155;margin-left:8px;">\n <input type="checkbox" name="exclude_customer_projects" value="yes" {% if exclude_customer_projects == 'yes' %}checked{% endif %}>\n Für Kundenprojekte bereits ausgewertete ausblenden\n </label>\n'''
if anchor not in s: raise SystemExit('checkbox anchor missing')
s=s.replace(anchor,insert+anchor,1)
# unchecked checkbox must submit no; JS sync hidden field
s=s.replace(''' {% if tag_filter %}<input type="hidden" name="tag" value="{{ tag_filter }}">{% endif %}\n''',''' {% if tag_filter %}<input type="hidden" name="tag" value="{{ tag_filter }}">{% endif %}\n <input type="hidden" id="exclude-cp-fallback" name="exclude_customer_projects" value="no">\n''',1)
meta=''' <div class="result-score">Score {{ r.search_score }}</div>\n'''
meta2=''' <div>\n <div class="result-score">Score {{ r.search_score }}</div>\n {% if r.customer_project_analysis %}\n {% if r.customer_project_analysis.status == 'processed' %}<span class="analysis-badge analysis-done">Kundenprojekte · ausgewertet</span>{% elif r.customer_project_analysis.status == 'transcript_missing' %}<span class="analysis-badge analysis-missing">Kundenprojekte · Transkript fehlt</span>{% endif %}\n {% endif %}\n </div>\n'''
if meta not in s: raise SystemExit('badge anchor missing')
s=s.replace(meta,meta2,1)
# keep helper links preserving filter
s=s.replace('build_search_url(q=query, sort=sort, limit=limit_param)', 'build_search_url(q=query, sort=sort, limit=limit_param, exclude_customer_projects=exclude_customer_projects)')
s=s.replace('build_search_url(q=query, tag=item.key, sort=sort, limit=limit_param)', 'build_search_url(q=query, tag=item.key, sort=sort, limit=limit_param, exclude_customer_projects=exclude_customer_projects)')
s=s.replace('build_search_url(q=query, tag=tag.key, sort=sort, limit=limit_param)', 'build_search_url(q=query, tag=tag.key, sort=sort, limit=limit_param, exclude_customer_projects=exclude_customer_projects)')
p.write_text(s)
print('TEMPLATE_PATCHED')