# build_hg_viewer.py
import os
from supabase import create_client
from dotenv import load_dotenv
load_dotenv()
SUPABASE_URL = os.environ["SUPABASE_URL"]
SUPABASE_SERVICE_ROLE = os.environ["SUPABASE_SERVICE_ROLE"]
if not SUPABASE_URL or not SUPABASE_SERVICE_ROLE:
raise RuntimeError("Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE")
supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE)
from upload_weblink_to_supabase import extract_paragraphs
# ======== HTML TEMPLATE ========
VIEW_TEMPLATE = """
Hochschulgesetz NRW – Paragraph Viewer
Hochschulgesetz NRW – Paragraph Viewer
⬆️ Top
"""
# -------------------------------------------------------------------
# 2. BUILD VIEWER
# -------------------------------------------------------------------
def build_html_from_db():
"""
Liest alle Paragraphen aus hg_nrw und baut daraus HTML.
"""
print(">>> Lade Paragraphen aus Supabase (hg_nrw) …")
paras = extract_paragraphs()
# 5.12_2:13
res = supabase.table("hg_nrw").select("*").order("order_index").execute()
rows = res.data or []
sidebar_links = ""
content_html = ""
for p in paras:
pid = p["abs_id"]
title = p["title"]
body = p["content"]
# Sidebar item
sidebar_links += f'\n'
# Fußnoten tách riêng (bắt đầu bằng "Fn 1", "Fn 2", ...)
lines = body.split("\n")
main_text = []
fn_text = []
in_fn = False
for line in lines:
if line.startswith("Fn "):
in_fn = True
if in_fn:
fn_text.append(line)
else:
main_text.append(line)
footnotes_html = ""
if fn_text:
footnotes_html += ''
footnotes_html += '
Fußnoten:
'
for fn in fn_text:
footnotes_html += f'
{fn}
'
footnotes_html += "
"
# Paragraph block
content_html += f"""
{title}
{'
'.join(main_text)}
{footnotes_html}
"""
html = VIEW_TEMPLATE.replace("", sidebar_links)
html = html.replace("", content_html)
return html
# -------------------------------------------------------------------
# 3. UPLOAD TO SUPABASE STORAGE
# -------------------------------------------------------------------
def upload_html():
html = build_html_from_db()
supabase.storage.from_("hg_viewer").update(
"hg_clean.html",
html.encode("utf-8"),
{
"content-type": "text/html",
"x-upsert": "true"
}
)
print("✔ hg_clean.html uploaded!")
if __name__ == "__main__":
upload_html()