"""Combine the 12 monthly sales files into one table and total them by product and by month.

Made for the practice files "Padma sales 2025-26" (smartaccountantbd.com/ai/trends/). Fictional data.

How to run (Windows):
  1. Install Python from python.org (tick "Add python.exe to PATH"), then in Command Prompt:
         pip install pandas openpyxl
  2. Put this file next to the folder "Padma sales 2025-26" and run:
         python combine_sales_working.py
  3. Open Padma_sales_summary.xlsx. The last lines on screen are the checks: compare the grand total
     with the total you know from your own books.

What it does that the first AI scripts did not:
  * looks for the header row (a title can sit above it) and finds each column by its name, in any order;
  * accepts "Product" or "Product name", and "Amount" or "Amount (Tk)";
  * turns text numbers like "1,25,000" into numbers, and keeps negative amounts (returns);
  * drops the "Total" rows, blank rows and anything without a date, and says how many it dropped;
  * treats "Carton 5-ply", "carton 5-ply " and " CARTON 5-PLY" as one product;
  * reads dates day first (Jan is a CSV with 13/01/2026 style dates) and stops if any date or amount is unreadable.
"""
from pathlib import Path

import pandas as pd

FOLDER = Path("Padma sales 2025-26")
OUT = Path("Padma_sales_summary.xlsx")

# Names we accept for each column (lower case, without the "(tk)" part)
NAMES = {
    "date": "Date", "invoice no.": "Invoice no.", "customer": "Customer",
    "product": "Product", "product name": "Product", "qty": "Qty",
    "unit price": "Unit price", "amount": "Amount",
}


def clean_name(text) -> str:
    return str(text).strip().lower().replace("(tk)", "").strip()


def read_one(path: Path) -> pd.DataFrame:
    if path.suffix.lower() == ".csv":
        raw = pd.read_csv(path, header=None, dtype=str, encoding="utf-8-sig", keep_default_na=False)
    else:
        raw = pd.read_excel(path, header=None, dtype=object)
    # the header row is the first row that has a "Date" cell
    header_at = next(i for i in range(len(raw)) if "date" in [clean_name(v) for v in raw.iloc[i]])
    table = raw.iloc[header_at + 1:].copy()
    table.columns = [NAMES.get(clean_name(v), str(v)) for v in raw.iloc[header_at]]
    table = table[list(dict.fromkeys(NAMES.values()))]          # keep our 7 columns, in our order
    table["File"] = path.name
    return table


def to_number(series: pd.Series) -> pd.Series:
    text = series.astype(str).str.replace(",", "", regex=False).str.strip()
    return pd.to_numeric(text.replace({"": None, "None": None, "nan": None}), errors="coerce")


files = sorted(p for p in FOLDER.iterdir() if p.suffix.lower() in {".xlsx", ".xls", ".csv"} and not p.name.startswith("~$"))
print(f"Found {len(files)} files")
frames = [read_one(p) for p in files]
rows = pd.concat(frames, ignore_index=True)

rows["Date"] = pd.to_datetime(rows["Date"], dayfirst=True, errors="coerce")
rows["Qty"] = to_number(rows["Qty"])
rows["Unit price"] = to_number(rows["Unit price"])
rows["Amount"] = to_number(rows["Amount"])

has_date = rows["Date"].notna()
print(f"Dropped {(~has_date).sum()} rows with no date (the Total rows and blank rows)")
rows = rows[has_date].copy()

bad = rows[rows["Amount"].isna()]
if len(bad):
    raise SystemExit(f"{len(bad)} rows have an amount that cannot be read, e.g. in {bad['File'].iloc[0]}. Stopping.")

rows["Product"] = rows["Product"].astype(str).str.strip().str.lower().str.capitalize()
rows["Month"] = rows["Date"].dt.to_period("M").astype(str)

by_product = rows.groupby("Product", as_index=False)["Amount"].sum().sort_values("Amount", ascending=False)
by_month = rows.groupby("Month", as_index=False)["Amount"].sum()
grid = rows.pivot_table(index="Product", columns="Month", values="Amount", aggfunc="sum", fill_value=0, margins=True, margins_name="Total")

with pd.ExcelWriter(OUT, engine="openpyxl") as writer:
    by_product.to_excel(writer, sheet_name="By product", index=False)
    by_month.to_excel(writer, sheet_name="By month", index=False)
    grid.to_excel(writer, sheet_name="Product by month")
    rows.drop(columns=["Month"]).to_excel(writer, sheet_name="All sales lines", index=False)

print(f"{len(rows)} sales lines, {rows['Product'].nunique()} products, {rows['Month'].nunique()} months")
print(f"Grand total: Tk {rows['Amount'].sum():,.0f}   <- check this against your own books")
print(f"Saved {OUT}")
