import pdfplumber
import pandas as pd
import re
import sys
from tqdm import tqdm


def parse_bidpac(pdf_path: str, output_path: str):
    rows = []

    with pdfplumber.open(pdf_path) as pdf:
        progress = tqdm(pdf.pages, total=len(pdf.pages), desc="Parsing pages", unit="page")

        for page_num, page in enumerate(progress, start=1):
            words = page.extract_words()
            current_person = None

            for w in words:
                text = w["text"]

                if re.match(r"^\d{5}\s*/\s*\d{6}$", text):
                    current_person = {
                        "crew_code": text,
                        "name": None,
                    }

                elif current_person and current_person["name"] is None and text.isalpha():
                    current_person["name"] = text

                elif current_person and re.match(r"^M\d{4}$", text):
                    rows.append({
                        "page": page_num,
                        "crew_code": current_person["crew_code"],
                        "name": current_person["name"],
                        "flight_no": text,
                        "x": w["x0"],
                        "y": w["top"],
                    })

            progress.set_postfix(rows=len(rows))

    df = pd.DataFrame(rows)
    df.to_csv(output_path, index=False)
    print(f"\nParsed {len(df)} rows to {output_path}")


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python parse_bidpac.py input.pdf output.csv")
        sys.exit(1)

    parse_bidpac(sys.argv[1], sys.argv[2])