"""Read the companion supplier.csv with four readers. Writes only to stdout and a temporary directory."""
import argparse
import csv
import platform
from pathlib import Path
import subprocess
import sys
import tempfile
from decimal import Decimal
from xml.etree import ElementTree
from zipfile import ZipFile

import duckdb
import pandas as pd
from openpyxl import load_workbook

FIELDS = ["sku", "parcel_id", "collection"]
XML = {"x": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}

def calc_rows(source, executable, directory, text):
    output = directory / ("text" if text else "standard")
    output.mkdir()
    profile = (directory / "profile").as_uri()
    # Column pairs are one-based position / format (2 = Text). Quantity stays numeric.
    formats = "1/2/2/2/3/2" if text else ""
    options = f"44,34,76,1,{formats},0,false,false"
    subprocess.run([executable, "-env:UserInstallation=" + profile, "--headless",
                    "--infilter=Text - txt - csv (StarCalc):" + options,
                    "--convert-to", "xlsx", "--outdir", str(output), str(source)],
                   check=True, stdout=subprocess.DEVNULL, timeout=45)
    workbook = output / (source.stem + ".xlsx")
    values = load_workbook(workbook, read_only=True).active
    with ZipFile(workbook) as package:
        sheet = ElementTree.fromstring(package.read("xl/worksheets/sheet1.xml"))
    # Preserve the decimal actually serialized by Calc without a second float conversion.
    cells = {cell.attrib["r"]: cell for cell in sheet.findall(".//x:c", XML)}
    result = []
    for row in list(values.rows)[1:]:
        record = {}
        for index, key in enumerate(FIELDS):
            cell = row[index]
            if cell.data_type == "n":
                value = cells[cell.coordinate].findtext("x:v", namespaces=XML)
                record[key] = format(Decimal(value), "f")
            else:
                record[key] = str(cell.value)
        result.append(record)
    return result

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--soffice", default="soffice")
    parser.add_argument("--csv", type=Path, default=Path(__file__).with_name("supplier.csv"))
    args = parser.parse_args()
    source = args.csv.resolve()
    with source.open(encoding="utf-8", newline="") as stream:
        reference = list(csv.DictReader(stream))
    if not reference or set(reference[0]) != set(FIELDS + ["quantity"]):
        parser.error("Use a nonempty file with sku, parcel_id, collection and quantity columns.")
    version = subprocess.check_output([args.soffice, "--version"], text=True).strip()
    cases = [("Python csv", platform.python_version(), "default", reference)]
    for mode, frame in [
        ("automatic", pd.read_csv(source)),
        ("explicit text", pd.read_csv(source, dtype={key: "string" for key in FIELDS}, keep_default_na=False))
    ]:
        cases.append(("pandas", pd.__version__, mode, frame.to_dict("records")))
    with duckdb.connect(":memory:") as con:
        for mode, settings in [("automatic", {}), ("explicit text", {"dtype": {key: "VARCHAR" for key in FIELDS}})]:
            relation = con.read_csv(str(source), header=True, **settings).select(*FIELDS)
            records = [dict(zip(FIELDS, row)) for row in relation.fetchall()]
            cases.append(("DuckDB", duckdb.__version__, mode, records))
    with tempfile.TemporaryDirectory() as temp:
        for text in [False, True]:
            cases.append(("LibreOffice Calc", version, "explicit text" if text else "automatic",
                          calc_rows(source, args.soffice, Path(temp), text)))
    out = csv.writer(sys.stdout, lineterminator="\n")
    out.writerow(["reader", "version", "mode", "field", "matches", "rows", "distinct", "imported_values_in_row_order"])
    for reader, version, mode, records in cases:
        if len(records) != len(reference):
            raise ValueError(f"{reader} returned {len(records)} rows; expected {len(reference)}")
        for key in FIELDS:
            values = [str(row[key]) for row in records]
            matches = sum(value == ref[key] for value, ref in zip(values, reference))
            out.writerow([reader, version, mode, key, matches, len(reference), len(set(values)), " | ".join(values)])

if __name__ == "__main__":
    main()
