#!/usr/bin/env python3
"""
fill_pdf.py — Remplit le PDF AcroForm officiel du constat amiable + estampilles.

Usage:
  python3 fill_pdf.py <template.pdf> <data.json> <output.pdf>

data.json (format étendu) :
{
  "fields": { "nom_champ_acroform": valeur, ... },   // champs AcroForm
  "stamps": {                                        // estampilles (optionnel)
    "chocA": {"x": 0.5, "y": 0.3},                   // point de choc (relatif silhouette)
    "chocB": {"x": 0.7, "y": 0.6},
    "signatureA": "<base64 png>",                    // signature conducteur A
    "signatureB": "<base64 png>",
    "croquis": "<base64 png>"                        // croquis de l'accident
  }
}

Rétrocompat : si data.json est plat (pas de clé "fields"), tout est traité comme fields.

Valeurs :
  - Text        -> string
  - CheckBox    -> true/false
  - RadioButton -> "yes"/"no" (état d'export du bouton)

Pages du PDF source (6 pages) :
  0 = instructions FR (à supprimer)
  1 = formulaire principal (recto) — GARDER
  2 = copie identique (à supprimer)
  3 = déclaration (verso) — GARDER
  4 = notes complémentaires — GARDER
  5 = instructions FR part 2 (à supprimer)
Résultat : 3 pages (formulaire + déclaration + notes).
"""
import sys, json, re, base64, fitz

KEEP_PAGES = [1, 3, 4]  # indices des pages à conserver

# --- Géométrie des estampilles (page 1, en points PDF) ---
# Silhouettes de voiture (point de choc) : x0, y0, x1, y1
CAR_A = (17.8, 661.4, 110.3, 734.4)
CAR_B = (481.2, 661.4, 573.8, 734.4)
# Zones signatures (bloc 15)
SIG_A = (205, 820, 290, 855)
SIG_B = (290, 820, 375, 855)
# Zone croquis (bloc 13)
CROQUIS = (214, 630, 378, 795)


def on_state(doc, w):
    """État d'export d'un widget radio (celui qui n'est pas 'Off')."""
    try:
        wd = doc.xref_object(w.xref)
        m = re.search(r'/AP (\d+) 0 R', wd)
        if not m:
            return None
        ap = doc.xref_object(int(m.group(1)))
        m2 = re.search(r'/N (\d+) 0 R', ap)
        if not m2:
            return None
        n = doc.xref_object(int(m2.group(1)))
        states = re.findall(r'/(\w+) \d+ 0 R', n)
        for s in states:
            if s != 'Off':
                return s
    except Exception:
        pass
    return None


def fill_fields(doc, fields):
    """Remplit les champs AcroForm. Corrige le bug radio (ne coche que le bon widget)."""
    filled = 0
    skipped = []

    # Grouper les widgets radio par nom (2 widgets par groupe : no + yes)
    radio_groups = {}
    for page in doc:
        for w in page.widgets():
            if w.field_type == fitz.PDF_WIDGET_TYPE_RADIOBUTTON:
                radio_groups.setdefault(w.field_name, []).append(w)

    for page in doc:
        for w in page.widgets():
            name = w.field_name
            if name not in fields:
                continue
            val = fields[name]
            try:
                if w.field_type == fitz.PDF_WIDGET_TYPE_RADIOBUTTON:
                    # Ne cocher que le widget dont l'état d'export == valeur cible
                    target = str(val)
                    on = on_state(doc, w)
                    w.field_value = (on == target)
                    w.update()
                    filled += 1
                elif w.field_type == fitz.PDF_WIDGET_TYPE_CHECKBOX:
                    w.field_value = bool(val)
                    w.update()
                    filled += 1
                else:  # Text
                    w.field_value = str(val)
                    w.update()
                    filled += 1
            except Exception as e:
                skipped.append(f"{name}: {e}")

    return filled, skipped


def stamp_choc(page, car, rel_x, rel_y):
    """Dessine une croix rouge au point de choc sur la silhouette de voiture."""
    x0, y0, x1, y1 = car
    cx = x0 + rel_x * (x1 - x0)
    cy = y0 + rel_y * (y1 - y0)
    r = 6.0
    color = (1, 0, 0)
    width = 2.0
    page.draw_line(fitz.Point(cx - r, cy - r), fitz.Point(cx + r, cy + r), color=color, width=width)
    page.draw_line(fitz.Point(cx - r, cy + r), fitz.Point(cx + r, cy - r), color=color, width=width)


def stamp_image(page, rect, b64):
    """Insère une image (base64) dans un rectangle, en gardant les proportions."""
    if not b64:
        return
    if b64.startswith('data:'):
        b64 = b64.split(',', 1)[1]
    data = base64.b64decode(b64)
    page.insert_image(fitz.Rect(*rect), stream=data, keep_proportion=True)


def apply_stamps(doc, stamps):
    """Applique les estampilles (point de choc, signatures, croquis) sur la page 1."""
    if not stamps:
        return 0
    page = doc[1]  # formulaire recto
    n = 0
    if 'chocA' in stamps and isinstance(stamps['chocA'], dict):
        stamp_choc(page, CAR_A, float(stamps['chocA'].get('x', 0.5)), float(stamps['chocA'].get('y', 0.5)))
        n += 1
    if 'chocB' in stamps and isinstance(stamps['chocB'], dict):
        stamp_choc(page, CAR_B, float(stamps['chocB'].get('x', 0.5)), float(stamps['chocB'].get('y', 0.5)))
        n += 1
    if stamps.get('signatureA'):
        stamp_image(page, SIG_A, stamps['signatureA'])
        n += 1
    if stamps.get('signatureB'):
        stamp_image(page, SIG_B, stamps['signatureB'])
        n += 1
    if stamps.get('croquis'):
        stamp_image(page, CROQUIS, stamps['croquis'])
        n += 1
    return n


def fill_pdf(template_path, data_path, output_path):
    with open(data_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # Format étendu { fields, stamps } ou plat (rétrocompat)
    if isinstance(data, dict) and 'fields' in data:
        fields = data.get('fields', {})
        stamps = data.get('stamps', {})
    else:
        fields = data
        stamps = {}

    doc = fitz.open(template_path)

    filled, skipped = fill_fields(doc, fields)
    stamped = apply_stamps(doc, stamps)

    # Supprimer les pages inutiles (ordre décroissant pour ne pas décaler)
    all_pages = list(range(len(doc)))
    to_remove = [i for i in all_pages if i not in KEEP_PAGES]
    for idx in sorted(to_remove, reverse=True):
        doc.delete_page(idx)

    doc.save(output_path, deflate=True, garbage=3)
    doc.close()

    result = {"filled": filled, "skipped": skipped, "stamped": stamped, "pages": len(KEEP_PAGES)}
    print(json.dumps(result, ensure_ascii=False))
    return result


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("usage: fill_pdf.py <template.pdf> <data.json> <output.pdf>", file=sys.stderr)
        sys.exit(1)
    fill_pdf(sys.argv[1], sys.argv[2], sys.argv[3])
