#!/usr/bin/env python3
"""Turn a CSV export into a clean Excel report: bold header, frozen top row,
filters, sized columns, money formatting and a totals row.

    python3 csv_to_excel.py sales.csv                 # writes sales.xlsx
    python3 csv_to_excel.py sales.csv -o report.xlsx --money Amount Tax
"""
import argparse
import csv
from pathlib import Path

from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
from openpyxl.utils import get_column_letter


def to_number(text):
    t = text.strip().replace(",", "").replace("$", "")
    try:
        return int(t) if t.lstrip("-").isdigit() else float(t)
    except ValueError:
        return text


def convert(src, dst, money=()):
    with open(src, newline="", encoding="utf-8-sig") as f:
        rows = list(csv.reader(f))
    if not rows:
        raise SystemExit("The CSV is empty.")
    header, body = rows[0], [[to_number(c) for c in r] for r in rows[1:]]

    wb = Workbook()
    ws = wb.active
    ws.title = Path(src).stem[:31] or "Sheet1"
    ws.append(header)
    for r in body:
        ws.append(r)

    for cell in ws[1]:
        cell.font = Font(bold=True, color="FFFFFF")
        cell.fill = PatternFill("solid", fgColor="0E7C86")
    ws.freeze_panes = "A2"
    last_col = get_column_letter(len(header))
    ws.auto_filter.ref = f"A1:{last_col}{len(body) + 1}"

    numeric = [i for i in range(len(header))
               if body and all(isinstance(r[i], (int, float)) for r in body if i < len(r) and r[i] != "")]
    if body and numeric:
        total_row = len(body) + 2
        ws.cell(total_row, 1, "Total").font = Font(bold=True)
        for i in numeric:
            if i == 0:
                continue
            col = get_column_letter(i + 1)
            c = ws.cell(total_row, i + 1, f"=SUM({col}2:{col}{len(body) + 1})")
            c.font = Font(bold=True)

    for i, name in enumerate(header, start=1):
        if name in money:
            for (cell,) in ws.iter_rows(min_row=2, min_col=i, max_col=i):
                cell.number_format = '"$"#,##0.00'
        width = max([len(str(name))] + [len(str(r[i - 1])) for r in body if i - 1 < len(r)])
        ws.column_dimensions[get_column_letter(i)].width = min(width + 3, 60)

    wb.save(dst)
    return len(body)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("csv")
    ap.add_argument("-o", "--output")
    ap.add_argument("--money", nargs="*", default=[], help="column names to show as dollars")
    a = ap.parse_args(argv)
    out = a.output or str(Path(a.csv).with_suffix(".xlsx"))
    n = convert(a.csv, out, a.money)
    print(f"Wrote {n} rows to {out}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
