#!/usr/bin/env python3
"""gop_bang.py - Gop bang tu NHIEU file PDF trong 1 thu muc thanh 1 file Excel.
Cach dung:  python gop_bang.py <thu-muc-chua-pdf> [ten-file-ra.xlsx]
Can cai:    pip install pdfplumber openpyxl
- Moi dong ghi kem ten file PDF nguon de doi chieu.
- So kieu Viet Nam (85.000 / 1.250.000 / 2,5) duoc doi thanh SO THAT trong Excel,
  tranh bay mo CSV bi doi 85.000 thanh 85.
- File khong lay duoc bang nao (vd ban scan, khong co lop chu) duoc liet ke o sheet "Kiem tra".
Khong co OCR: file scan phai chay OCR truoc (vd Tesseract). Duy AI Lab, 25/11/2026.
"""
import re
import sys
from pathlib import Path

import pdfplumber
from openpyxl import Workbook

SO_VN = re.compile(r"^-?\d{1,3}(\.\d{3})+(,\d+)?$|^-?\d+(,\d+)?$")


def doi_so(o):
    if o is None:
        return ""
    t = " ".join(str(o).split())  # bo xuong dong trong o
    if SO_VN.match(t):
        t2 = t.replace(".", "").replace(",", ".")
        return float(t2) if "." in t2 else int(t2)
    return t


def main():
    if len(sys.argv) < 2:
        print("Cach dung: python gop_bang.py <thu-muc-pdf> [ket_qua.xlsx]")
        sys.exit(2)
    thu_muc = Path(sys.argv[1])
    ra = Path(sys.argv[2] if len(sys.argv) > 2 else "tong_hop.xlsx")
    wb = Workbook()
    ws = wb.active
    ws.title = "Tong hop"
    kt = wb.create_sheet("Kiem tra")
    kt.append(["File PDF", "So trang", "So bang", "So dong lay duoc", "Ghi chu"])
    tieu_de_da_ghi = False
    for pdf_path in sorted(thu_muc.glob("*.pdf")):
        so_bang = so_dong = 0
        with pdfplumber.open(pdf_path) as pdf:
            so_trang = len(pdf.pages)
            for page in pdf.pages:
                for bang in page.extract_tables() or []:
                    so_bang += 1
                    for i, dong in enumerate(bang):
                        hang = [doi_so(c) for c in dong]
                        if i == 0:  # dong tieu de cua bang
                            if not tieu_de_da_ghi:
                                ws.append(["File nguon"] + hang)
                                tieu_de_da_ghi = True
                            continue
                        ws.append([pdf_path.name] + hang)
                        so_dong += 1
        ghi_chu = "KHONG lay duoc bang: co the la ban scan, can OCR" if so_bang == 0 else (
            "It dong, kiem tra lai bang co bi lech khong" if so_dong < 3 else "")
        kt.append([pdf_path.name, so_trang, so_bang, so_dong, ghi_chu])
        print(f"{pdf_path.name}: {so_bang} bang, {so_dong} dong. {ghi_chu}")
    wb.save(ra)
    print("Da ghi:", ra)


if __name__ == "__main__":
    main()
