#!/usr/bin/env python3
"""Guess the next 8 weeks of one product's sales, and show how well each guess would have done.

    python3 forecast.py --demo                                  # made-up data; no file, no key
    python3 forecast.py --csv item-history.csv --product "Blue Dream 3.5g"
    python3 forecast.py --demo --hide-from 2026-03-22                # score them around last 4/20 instead
    python3 forecast.py --csv item-history.csv --product "Blue Dream 3.5g" --weekly-out weeks.csv  # for the sheet
    python3 forecast.py --distru --product-id <id> --since 2024-09-01 --dry-run
    python3 forecast.py --distru --product-id <id> --since 2024-09-01   # needs DISTRU_API_TOKEN

It totals sales into weeks (Sunday to Saturday), hides the last 8 finished weeks, and asks three
simple methods to forecast them from the week before:

  same as last week     next week = last week
  recent average        next week = average of the last N weeks (--window, default 4)
  last year's pattern   next week = the same week last year x (last 8 weeks / same 8 weeks last year)

It scores each on the hidden weeks (average units off per week, and percent off), then prints all
three forecasts for the next 8 weeks and says which one did best. Sunday weeks keep week t and
week t-52 on the same calendar dates (364 days apart), so 4/20 lines up with last year's 4/20.
Last year's pattern needs 68 finished weeks (60 to forecast, 8 to hide); with less it is skipped.

Input, any of:
  --csv   Distru's Sales Order Item History report exported as CSV (Reports in Distru), or the same
          report pulled with --distru, or any CSV with a date column and a quantity column
          (--date-col, --qty-col). Headers are matched loosely: "Order Date", "order_date" and
          "order date" are the same column. Canceled orders are skipped; returned quantity is
          subtracted when the column exists.
  --distru  GET /public/v1/reports/sales-order-item-history, one request per 90 days, samples
          excluded, canceled orders excluded. Order dates come back in your company's timezone.
          Read-only: it only sends GET requests. It never prints your key.

Standard library only. Python 3.9 or newer. From lesson 05-08 of Distru's No Bullshit AI Course.
Adapted in part from Microsoft's ML for Beginners (MIT License, Copyright (c) Microsoft Corporation);
not endorsed by Microsoft. CC0 1.0. Version 1.0.0 (2026-09-29).
"""
import argparse
import csv
import datetime as dt
import json
import math
import os
import random
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

HOLD = 8
SEASON = 52
BASE_URL = "https://app.distru.com/public/v1"
REPORT = "/reports/sales-order-item-history"
TOKEN_ENV = "DISTRU_API_TOKEN"
LIVE_STATUSES = ["PENDING", "PROCESSING", "READY_TO_SHIP", "DELIVERING", "DELIVERED", "COMPLETED"]


# ---------- reading sales ----------

def norm(name):
    return "".join(ch for ch in (name or "").lower() if ch.isalnum())


def pick(row_keys, wanted, flag):
    keys = {norm(k): k for k in row_keys}
    for w in wanted:
        if norm(w) in keys:
            return keys[norm(w)]
    sys.exit(f"Could not find a {flag.lstrip('-').replace('-col', '')} column. Columns are: "
             f"{', '.join(row_keys)}. Name it with {flag}.")


def parse_day(text):
    text = (text or "").strip()
    if not text:
        return None
    for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y"):
        try:
            return dt.datetime.strptime(text[:10] if fmt == "%Y-%m-%d" else text.split()[0], fmt).date()
        except ValueError:
            pass
    return None


def rows_to_daily(rows, date_col=None, qty_col=None, product=None):
    """rows: list of dicts. Returns {date: units}, and counts of what was skipped."""
    if not rows:
        sys.exit("No rows to read.")
    cols = list(rows[0].keys())
    dcol = date_col or pick(cols, ["order_date", "order date", "date", "week", "week starting"], "--date-col")
    qcol = qty_col or pick(cols, ["quantity", "qty", "units", "units sold"], "--qty-col")
    keys = {norm(k): k for k in cols}
    scol, rcol = keys.get("status"), keys.get("returnedquantity")
    pcols = [keys[k] for k in ("product", "productsku", "productid", "sku") if k in keys]
    daily, skipped = {}, {"canceled": 0, "other product": 0, "unreadable": 0}
    for r in rows:
        if product and not any((r.get(c) or "").strip().lower() == product.lower() for c in pcols):
            skipped["other product"] += 1
            continue
        if scol and "CANCEL" in (r.get(scol) or "").upper():
            skipped["canceled"] += 1
            continue
        day = parse_day(r.get(dcol))
        try:
            q = float((r.get(qcol) or "").replace(",", ""))
            if rcol and (r.get(rcol) or "").strip():
                q -= float(r[rcol].replace(",", ""))
        except ValueError:
            day = None
        if day is None:
            skipped["unreadable"] += 1
            continue
        daily[day] = daily.get(day, 0.0) + q
    if product and not daily:
        sys.exit(f'No rows matched --product "{product}". It must equal the product name, SKU or id exactly.')
    return daily, skipped


def week_start(day):
    return day - dt.timedelta(days=(day.weekday() + 1) % 7)  # back to Sunday


def to_weeks(daily, today):
    """Totals per Sunday week, with empty weeks as 0, dropping the week still in progress."""
    if not daily:
        sys.exit("No sales found.")
    first, this_week = week_start(min(daily)), week_start(today)
    totals = {}
    for day, q in daily.items():
        totals[week_start(day)] = totals.get(week_start(day), 0.0) + q
    weeks, w = [], first
    while w < this_week:
        weeks.append((w, totals.get(w, 0.0)))
        w += dt.timedelta(days=7)
    return weeks


def demo_weeks():
    """Two years of made-up weekly sales: growth, a 4/20 spike, holiday dips. Same shape as the lesson's toy."""
    rnd = random.Random(420)
    start, out = dt.date(2024, 9, 29), []
    for i in range(104):
        w = start + dt.timedelta(days=7 * i)
        has = lambda m, d: 0 <= (dt.date(w.year, m, d) - w).days < 7
        mult = 1 + 0.08 * math.sin(2 * math.pi * (i + 15) / 52)
        mult *= 2.1 if has(4, 20) else 1.25 if has(4, 13) else 1
        mult *= 0.72 if has(12, 25) else 0.8 if has(1, 1) else 1
        out.append((w, max(0, round((180 + 0.55 * i) * mult + rnd.gauss(0, 9)))))
    return out


# ---------- Distru ----------

def distru_rows(product_id, since, token, dry_run):
    start = dt.date.fromisoformat(since)
    end = dt.date.today() + dt.timedelta(days=1)
    rows = []
    while start < end:
        stop = min(start + dt.timedelta(days=90), end)
        last_day = stop - dt.timedelta(days=1)  # the range is inclusive; stop is the next chunk's first day
        params = [("order_datetime", f"{start}T00:00:00Z,{last_day}T23:59:59.999999Z"), ("sample", "EXCLUDE"),
                  ("product_ids[]", product_id)] + [("status[]", s) for s in LIVE_STATUSES]
        url = BASE_URL + REPORT + "?" + urllib.parse.urlencode(params)
        if dry_run:
            print("GET", url)
        else:
            req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}", "Accept": "application/json"})
            for attempt in range(3):
                try:
                    with urllib.request.urlopen(req, timeout=60) as resp:
                        rows += json.load(resp)["data"]
                    break
                except urllib.error.HTTPError as e:
                    if e.code == 429 and attempt < 2:
                        time.sleep(int(e.headers.get("Retry-After", "5")))
                        continue
                    body = e.read().decode("utf-8", "replace")[:500]
                    sys.exit(f"Distru answered {e.code} for {start}..{stop}: {body}")
            time.sleep(0.2)
        start = stop
    if dry_run:
        print(f"  Authorization: Bearer <{TOKEN_ENV}>\nNo request was sent.")
        sys.exit(0)
    return [{k: ("" if v is None else str(v)) for k, v in r.items()} for r in rows]


# ---------- forecasting ----------

def predict(ys, method, window, cut, horizon=HOLD):
    """Forecast ys[cut : cut+horizon] using only ys[:cut]."""
    if method == "naive":
        return [ys[cut - 1]] * horizon
    if method == "average":
        w = ys[max(0, cut - window):cut]
        return [sum(w) / len(w)] * horizon
    before = sum(ys[cut - 60:cut - 52])
    ratio = sum(ys[cut - 8:cut]) / before if before else 1.0
    return [ys[cut + k - SEASON] * ratio for k in range(horizon)]


def usable(n, method, cut):
    return method != "season" or cut >= SEASON + HOLD


NAMES = {"naive": "same as last week", "average": "recent average", "season": "last year's pattern"}


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    src = ap.add_mutually_exclusive_group(required=True)
    src.add_argument("--csv", help="a CSV of sales lines, or of weekly totals")
    src.add_argument("--distru", action="store_true", help="pull the Sales Order Item History report from Distru")
    src.add_argument("--demo", action="store_true", help="made-up data, to see what it does")
    ap.add_argument("--product", help="keep only rows whose product name, SKU or id equals this")
    ap.add_argument("--product-id", help="with --distru: the Distru product id")
    ap.add_argument("--since", help="with --distru: first day to pull, YYYY-MM-DD (two years back is ideal)")
    ap.add_argument("--date-col", help="name of the date column, if it is not found on its own")
    ap.add_argument("--qty-col", help="name of the quantity column, if it is not found on its own")
    ap.add_argument("--window", type=int, default=4, help="weeks in the recent average (default 4)")
    ap.add_argument("--hide-from", help="score on the 8 weeks starting the week of this date (YYYY-MM-DD) "
                    "instead of the last 8; use a date a few weeks before last 4/20 to see who catches the spike")
    ap.add_argument("--weekly-out", help="also write the weekly totals here, ready to paste into the sheet")
    ap.add_argument("--out", default="forecast.csv", help="where to write the forecast (default forecast.csv)")
    ap.add_argument("--dry-run", action="store_true", help="with --distru: print the requests, send nothing")
    a = ap.parse_args()

    skipped = {}
    if a.demo:
        weeks = demo_weeks()
    else:
        if a.distru:
            if not (a.product_id and a.since):
                sys.exit("--distru needs --product-id and --since.")
            token = os.environ.get(TOKEN_ENV, "")
            if not token and not a.dry_run:
                sys.exit(f"Set {TOKEN_ENV} first (Distru -> Settings -> Integrations -> Distru API). Never paste it into a chat.")
            rows = distru_rows(a.product_id, a.since, token, a.dry_run)
        else:
            with open(a.csv, newline="", encoding="utf-8-sig") as f:
                rows = list(csv.DictReader(f))
        daily, skipped = rows_to_daily(rows, a.date_col, a.qty_col, a.product)
        weeks = to_weeks(daily, dt.date.today())

    ys = [q for _, q in weeks]
    n = len(ys)
    if a.weekly_out:
        with open(a.weekly_out, "w", newline="") as f:
            w = csv.writer(f)
            w.writerow(["Week starting (Sunday)", "Units sold"])
            w.writerows((wk.isoformat(), int(q) if q == int(q) else round(q, 2)) for wk, q in weeks)
        print(f"Weekly totals written to {a.weekly_out}: paste columns A and B into the sheet.")
    if n < HOLD + max(2, a.window):
        sys.exit(f"Only {n} finished weeks. It needs at least {HOLD + max(2, a.window)}; two years is best.")
    cut = n - HOLD
    if a.hide_from:
        w0 = week_start(dt.date.fromisoformat(a.hide_from))
        starts = [w for w, _ in weeks]
        if w0 not in starts or starts.index(w0) + HOLD > n:
            sys.exit(f"--hide-from must fall in your data and leave {HOLD} weeks after it.")
        cut = starts.index(w0)
    methods = [m for m in NAMES if usable(n, m, cut)]

    print(f"{n} finished weeks, {weeks[0][0]} to {weeks[-1][0] + dt.timedelta(days=6)}; "
          f"{sum(ys):,.0f} units in total.")
    if any(skipped.values()):
        print("Skipped rows: " + ", ".join(f"{v} {k}" for k, v in skipped.items() if v))
    if "season" not in methods:
        print(f"Last year's pattern is skipped: it needs {SEASON + HOLD} finished weeks before the hidden ones.")
    zeros = sum(1 for y in ys if y == 0)
    if zeros > n // 4:
        print(f"Warning: {zeros} of {n} weeks sold nothing. Out-of-stock weeks look like no demand; "
              "a forecast learns that as a quiet week. Check them before you trust any of this.")

    actual = ys[cut:cut + HOLD]
    which = f"the {HOLD} weeks from {weeks[cut][0]}" if a.hide_from else f"the last {HOLD} weeks"
    print(f"\nHow each would have done on {which} (hidden from all of them):")
    head = f"{'week of':<11}{'actual':>8}" + "".join(f"{NAMES[m]:>21}" for m in methods)
    print(head)
    preds = {m: predict(ys, m, a.window, cut) for m in methods}
    for k in range(HOLD):
        print(f"{str(weeks[cut + k][0]):<11}{actual[k]:>8.0f}" + "".join(f"{preds[m][k]:>21.0f}" for m in methods))
    score = {}
    for m in methods:
        mae = sum(abs(p - y) for p, y in zip(preds[m], actual)) / HOLD
        pct = [abs(p - y) / y for p, y in zip(preds[m], actual) if y]
        score[m] = mae
        pct_txt = f"{100 * sum(pct) / len(pct):.0f}% off" if pct else "n/a"
        print(f"  {NAMES[m]:<21} off by {mae:,.1f} units a week on average ({pct_txt})")
    best = min(score, key=score.get)
    print(f"\nBest on the hidden weeks: {NAMES[best]}.")

    future = {m: predict(ys + [0.0] * HOLD, m, a.window, n) for m in NAMES if usable(n, m, n)}
    last = weeks[-1][0]
    with open(a.out, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["week_starting"] + [NAMES[m] for m in future])
        for k in range(HOLD):
            w.writerow([last + dt.timedelta(days=7 * (k + 1))] + [round(future[m][k]) for m in future])
    print(f"Next {HOLD} weeks, all three methods, written to {a.out}. Use the '{NAMES[best]}' column, "
          "and check it against anything you know is coming that last year did not have.")


if __name__ == "__main__":
    main()
