"""Weekly "will we ship?" check. No AI inside: same files in, same numbers out.

It moves the twin's start (time zero) to this week's Monday in a dated copy of the shop file,
runs the twin 20 times on this week's orders, adds one line to the weekly log,
compares the week to the last line in the log, and prints the result as JSON
for Claude to turn into the one-page call.

Usage (from the shop twin folder):
  python3 weekly_check.py --shop shop.yaml --orders data/orders.csv --log results/weekly-log.csv --week-start 2026-11-30
(--shop, --orders and --log default to shop.yaml, data/orders.csv and results/weekly-log.csv.)

It stops, with a plain message, when the data is bad. It never changes shop.yaml or the orders file.
"""
import argparse
import csv
import json
import os
import re
import subprocess
import sys
from datetime import date, timedelta

REPS = "20"
COLUMNS = ["work_order_id", "customer", "part", "qty", "start_date", "due_date", "priority"]
DROP_ALERT = 5.0  # on-time points lost in one week that count as an alert


def stop(message):
    print(json.dumps({"status": "STOPPED", "reason": message}))
    sys.exit(1)


def check_orders(path):
    if not os.path.exists(path):
        stop(f"{path} is not there. Make this week's orders file first.")
    with open(path, newline="") as handle:
        reader = csv.DictReader(handle)
        if reader.fieldnames != COLUMNS:
            stop(f"{path} header must be exactly: {','.join(COLUMNS)}")
        rows = list(reader)
    if not rows:
        stop(f"{path} has no orders.")
    seen = set()
    for line, row in enumerate(rows, start=2):
        if row["work_order_id"] in seen:
            stop(f"line {line}: work order {row['work_order_id']} is in the file twice.")
        seen.add(row["work_order_id"])
        if not row["qty"].isdigit() or int(row["qty"]) <= 0:
            stop(f"line {line}: qty must be a whole number above 0. It says \"{row['qty']}\".")
        for column in ("start_date", "due_date"):
            if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", row[column]):
                stop(f"line {line}: {column} must look like 2026-11-30. It says \"{row[column]}\".")
        if row["due_date"] < row["start_date"]:
            stop(f"line {line}: {row['work_order_id']} is due before it is released.")
    return rows


def week_shop(shop, week_start, out_dir):
    """A copy of the shop file with time zero moved to this week's Monday. shop.yaml is never changed."""
    with open(shop) as handle:
        text = handle.read()
    found = re.findall(r'origin: "(\d{4}-\d{2}-\d{2})', text)
    if not found:
        stop(f"{shop} has no calendar origin. The owner needs to look at the shop file.")
    text = re.sub(r'origin: "\d{4}-\d{2}-\d{2}', f'origin: "{week_start}', text)
    os.makedirs(out_dir, exist_ok=True)
    path = os.path.join(out_dir, f"shop-week-{week_start}.yaml")
    with open(path, "w") as handle:
        handle.write(text)
    return path


def twinflow(command, args):
    result = subprocess.run(command + args, capture_output=True, text=True)
    if result.returncode != 0:
        stop("twinflow stopped: " + (result.stderr.strip() or result.stdout.strip())[-600:])
    return result.stdout


def run_week(command, shop, orders, sweep):
    out = twinflow(command, ["run", shop, "--plan", orders, "--reps", REPS, "--orders"])
    late = []
    for line in out.splitlines():
        match = re.match(r"(\S+)\s+(\S+)\s+(\d+)\s+(.+?)\s{2,}(.+?)\s{2,}(.+?)\s{2,}(\d+) of (\d+)$", line.strip())
        if match and int(match.group(7)) >= 5:
            late.append({"order": match.group(1), "part": match.group(2), "qty": int(match.group(3)),
                         "due": match.group(4), "typical_finish": match.group(5),
                         "bad_case_finish": match.group(6), "late_in": f"{match.group(7)} of {match.group(8)}"})
    run_dir = re.search(r"dir:\s+(\S+)", out).group(1)
    with open(os.path.join(run_dir, "kpis.json")) as handle:
        hours = json.load(handle)["machine_hours_by_machine"]
    busiest = max(hours, key=hours.get)
    out = twinflow(command, ["balance", shop, "--plan", orders, "--sweep", sweep, "--reps", REPS])
    summary_path = re.search(r"summary:\s+(\S+)", out).group(1)
    with open(summary_path) as handle:
        point = json.load(handle)[0]
    return {"on_time_pct": point["on_time_pct"], "late_orders_per_run": point["late_orders_per_run"],
            "busiest_machine": busiest, "busiest_machine_hours_run1": round(hours[busiest], 1),
            "orders_at_risk": late, "run_dir": run_dir}


def last_line(log):
    if not os.path.exists(log):
        return None
    with open(log, newline="") as handle:
        rows = list(csv.DictReader(handle))
    return rows[-1] if rows else None


def find_twinflow():
    """The twinflow command from the house rules in CLAUDE.md, else a twin-flow folder here or at home."""
    if os.path.exists("CLAUDE.md"):
        with open("CLAUDE.md") as handle:
            match = re.search(r"uv run --project (\S+) twinflow", handle.read())
        if match and "<" not in match.group(1):
            return f"uv run --project {match.group(1)} twinflow"
    for folder in ("twin-flow", os.path.expanduser("~/twin-flow")):
        if os.path.isdir(folder):
            return f"uv run --project {folder} twinflow"
    stop("cannot find twin-flow. Put its folder in the first house rule in CLAUDE.md.")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--shop", default="shop.yaml")
    parser.add_argument("--orders", default="data/orders.csv")
    parser.add_argument("--sweep", default="whatif/today.json", help="the one-point sweep that changes nothing")
    parser.add_argument("--log", default="results/weekly-log.csv")
    parser.add_argument("--twinflow", help="how to run twinflow (default: from CLAUDE.md)")
    parser.add_argument("--week-start", help="this week's Monday, like 2026-11-30 (default: the last Monday)")
    args = parser.parse_args()
    today = date.today()
    week_start = args.week_start or (today - timedelta(days=today.weekday())).isoformat()
    if date.fromisoformat(week_start).weekday() != 0:
        stop(f"--week-start {week_start} is not a Monday.")

    rows = check_orders(args.orders)
    if not os.path.exists(args.sweep):
        stop(f"{args.sweep} is not there. It is the one-point sweep from Part 2.")
    shop = week_shop(args.shop, week_start, os.path.join(os.path.dirname(args.log) or ".", "weeks"))
    week = run_week((args.twinflow or find_twinflow()).split(), shop, args.orders, args.sweep)
    before = last_line(args.log)
    change = None if before is None else round(week["on_time_pct"] - float(before["on_time_pct"]), 1)
    alert = change is not None and change <= -DROP_ALERT
    entry = {"date": today.isoformat(), "week_start": week_start, "orders_file": args.orders, "orders": len(rows),
             "on_time_pct": week["on_time_pct"], "late_orders_per_run": week["late_orders_per_run"],
             "busiest_machine": week["busiest_machine"], "orders_at_risk": len(week["orders_at_risk"]),
             "change_vs_last": "" if change is None else change, "alert": "ALERT" if alert else "",
             "approved_by": ""}
    os.makedirs(os.path.dirname(args.log) or ".", exist_ok=True)
    new_file = not os.path.exists(args.log)
    with open(args.log, "a", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(entry))
        if new_file:
            writer.writeheader()
        writer.writerow(entry)
    print(json.dumps({"status": "OK", **entry, "orders_at_risk_detail": week["orders_at_risk"],
                      "run_dir": week["run_dir"]}, indent=1))


if __name__ == "__main__":
    main()
