#!/usr/bin/env python3
import os, json, argparse, sys
from pathlib import Path

# Importă scriptul tău existent form_parser_batchv7.py dacă e disponibil în PYTHONPATH sau același folder
try:
    import form_parser_batchv7 as v7
except Exception as e:
    print(json.dumps({"error": f"Cannot import form_parser_batchv7.py: {e}"}))
    sys.exit(1)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--file", required=True, help="Calea către fișierul PDF/IMG")
    args = ap.parse_args()

    cred = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
    if not cred or not Path(cred).exists():
        print(json.dumps({"error":"Missing GOOGLE_APPLICATION_CREDENTIALS or file not found"}))
        sys.exit(2)

    p = Path(args.file)
    if not p.exists():
        print(json.dumps({"error":"file not found"})); sys.exit(3)

    try:
        doc = v7.process_file(p)  # funcție din scriptul tău
        full_text = getattr(doc, "text", "") or ""

        # Încearcă să extragi câmpuri dacă există funcția
        fields = {}
        try:
            serie, numar, cnp, diag, nume, prenume, cod_parafa, investigatii, cui, boxes, data_prez = v7.extract_values(doc)
            fields = {
                "Serie": serie, "Numar": numar, "CNP": cnp, "Cod_diagnostic": diag,
                "Nume": nume, "Prenume": prenume, "Cod_parafa": cod_parafa,
                "Investigatii_recomandate": investigatii, "CUI": cui, "Data_prezentarii": data_prez
            }
        except Exception:
            pass

        print(json.dumps({"text": full_text, "fields": fields}, ensure_ascii=False))
    except Exception as e:
        print(json.dumps({"error": str(e)}))
        sys.exit(4)

if __name__ == "__main__":
    main()
