#!/usr/bin/env python3

import argparse
import json
from pathlib import Path

import fitz


TRUTHY_VALUES = {"1", "true", "yes", "y", "sim", "s", "checked", "x", "on"}


def is_truthy(value) -> bool:
    return str(value or "").strip().lower() in TRUTHY_VALUES


def load_values(path: Path) -> dict[str, str]:
    raw = json.loads(path.read_text())
    values: dict[str, str] = {}

    if isinstance(raw, dict):
      return {
          str(key): "" if value is None else str(value)
          for key, value in raw.items()
          if str(key).strip()
      }

    if isinstance(raw, list):
        for item in raw:
            if not isinstance(item, dict):
                continue
            field_name = str(item.get("pdfFieldName", "")).strip()
            if not field_name:
                continue
            values[field_name] = "" if item.get("value") is None else str(item.get("value"))

    return values


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--values", required=True)
    args = parser.parse_args()

    input_path = Path(args.input)
    output_path = Path(args.output)
    values = load_values(Path(args.values))

    document = fitz.open(input_path)
    updated_fields = 0

    for page in document:
        widgets = page.widgets() or []

        for widget in widgets:
            field_name = str(widget.field_name or "").strip()
            if not field_name or field_name not in values:
                continue

            raw_value = values[field_name]
            text_value = str(raw_value or "").strip()

            try:
                if widget.field_type == 2:
                    widget.field_value = widget.on_state() if is_truthy(text_value) else "Off"
                else:
                    widget.field_value = text_value

                widget.update()
                updated_fields += 1
            except Exception:
                continue

    document.save(output_path, garbage=4, deflate=True)
    print(json.dumps({"updatedFields": updated_fields, "pageCount": document.page_count}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
