# ==========================================
# OCR DETAIL MERGE
# ==========================================

import json
import os

from paddleocr import PaddleOCR

OUTPUT_DIR = r"G:\00. PROJECTS\API\Inventory\output"

DETAIL_COLUMNS = [

    "NamaBarang",
    "Jumlah",
    "Satuan",
    "SubTotal"

]

Y_TOLERANCE = 8

# ==========================================
# INIT OCR
# ==========================================

print("Loading PaddleOCR...")

ocr = PaddleOCR(
    use_angle_cls=True,
    lang="en"
)

print("Ready")
print("")

# ==========================================
# OCR COLUMN
# ==========================================

def read_column(column_name):

    file_name = os.path.join(
        OUTPUT_DIR,
        f"{column_name}.jpg"
    )

    result = ocr.ocr(
        file_name,
        cls=True
    )

    rows = []

    if not result or not result[0]:

        return rows

    for line in result[0]:

        try:

            box = line[0]

            text = line[1][0]

            conf = line[1][1]

            y = int(box[0][1])

            rows.append({

                "y": y,
                "text": text,
                "conf": conf

            })

        except:

            pass

    return rows

# ==========================================
# READ ALL COLUMNS
# ==========================================

columns = {}

for col in DETAIL_COLUMNS:

    rows = read_column(col)

    columns[col] = rows

    print("")
    print("=====", col, "=====")

    for r in rows:

        print(
            f"Y={r['y']:4d} "
            f"C={r['conf']:.2f} "
            f"{r['text']}"
        )

# ==========================================
# MASTER = NAMABARANG
# ==========================================

master_rows = []

for r in columns["NamaBarang"]:

    text_upper = r["text"].upper()

    if "NAMA" in text_upper:
        continue

    master_rows.append(r)

# ==========================================
# MERGE
# ==========================================

detail = []

for master in master_rows:

    item = {}

    master_y = master["y"]

    item["NamaBarang"] = master["text"]

    for col in DETAIL_COLUMNS:

        if col == "NamaBarang":
            continue

        item[col] = ""

        for r in columns[col]:

            text_upper = r["text"].upper()

            if col == "Satuan":

                if "SATUAN" in text_upper:
                    continue

            if col == "SubTotal":

                if "JUMLAH" in text_upper:
                    continue

                if "BERSIH" in text_upper:
                    continue

            if abs(r["y"] - master_y) <= Y_TOLERANCE:

                item[col] = r["text"]
                break

    detail.append(item)

# ==========================================
# RESULT
# ==========================================

print("")
print("===== DETAIL JSON =====")
print("")

print(
    json.dumps(
        detail,
        indent=2,
        ensure_ascii=False
    )
)

print("")
print("======================")