#!/usr/bin/env python3
"""Build the interactive PDF: insert text / one-char widgets (light highlight)
and a submit button POSTing the filled PDF to the bibletime backend."""
import fitz, json, os

SRC = "data/Level2_WhatChristiansBelieve.pdf"
OUT = "forms/Level2_WhatChristiansBelieve-form.pdf"
LESSON = "level2-what-christians-believe"
SUBMIT_URL = f"https://bibletime.org.ua/submit.php?lesson={LESSON}"

HILITE = (1, 0.97, 0.72)     # pale yellow highlight
BORDER = (0.80, 0.74, 0.45)  # soft border
os.makedirs("forms", exist_ok=True)

fields = json.load(open("fields.json"))
doc = fitz.open(SRC)

def add_text(page, name, rect, char=False):
    r = fitz.Rect(rect)
    w = fitz.Widget()
    w.field_name = name
    w.field_type = fitz.PDF_WIDGET_TYPE_TEXT
    w.rect = r
    w.fill_color = HILITE
    w.border_color = BORDER
    w.border_width = 0.5
    w.text_color = (0, 0, 0.55)
    if char:
        w.text_maxlen = 1
        w.text_align = fitz.TEXT_ALIGN_CENTER
        w.text_fontsize = 0          # auto-fit
    else:
        w.text_align = fitz.TEXT_ALIGN_LEFT
        w.text_fontsize = 11 if r.height < 26 else 10
        if r.height >= 26:           # tall box -> multiline
            w.field_flags = fitz.PDF_TX_FIELD_IS_MULTILINE
    page.add_widget(w)

n_char = n_text = 0
for pi, page in enumerate(doc):
    for f in fields[str(pi)]:
        if f["type"] == "char":
            add_text(page, f["name"], f["rect"], char=True); n_char += 1
        else:
            add_text(page, f["name"], f["rect"], char=False); n_text += 1

# ---- submit button on the back cover, in the empty band (no overlap) ----
last = doc[-1]
bw, bh = 180, 34
cx = last.rect.width / 2
by = 455                              # empty red band, above the title band
brect = fitz.Rect(cx - bw/2, by, cx + bw/2, by + bh)
# small instruction above the button (Cyrillic -> needs a Unicode font)
CYR_FONT = "/System/Library/Fonts/Supplemental/Arial.ttf"
try:
    last.insert_text((cx - bw/2, by - 10), "Заполнил? Отправь учителю:",
                     fontsize=11, color=(1, 1, 1), fontfile=CYR_FONT, fontname="cyr")
except Exception:
    last.insert_text((cx - bw/2, by - 10), "Filled it in? Send to your teacher:",
                     fontsize=11, color=(1, 1, 1))
btn = fitz.Widget()
btn.field_name = "submit_btn"
btn.field_type = fitz.PDF_WIDGET_TYPE_BUTTON
btn.field_flags = fitz.PDF_BTN_FIELD_IS_PUSHBUTTON
btn.rect = brect
btn.fill_color = (0.13, 0.55, 0.13)
btn.border_color = (0.10, 0.40, 0.10)
btn.border_width = 1
btn.text_color = (1, 1, 1)
btn.text_fontsize = 13
try:
    btn.button_caption = "Отправить"
except Exception:
    btn.button_caption = "Send"
btn.script = (f'this.submitForm({{cURL: "{SUBMIT_URL}", cSubmitAs: "PDF"}});')
last.add_widget(btn)

# make viewers regenerate field appearances
try:
    doc.set_need_appearances(True)
except Exception:
    pass

doc.save(OUT, deflate=True, garbage=3)
print(f"saved {OUT}: char={n_char} text={n_text} + submit_btn -> {SUBMIT_URL}")
