"""Build a weekly report deck from a CSV and convert it with the SlidesMate Markdown API."""
import csv
import json
import os
import sys
import urllib.error
import urllib.request

API_URL = "https://slidesmate.com/api/markdown"
MAX_CHARS = 100_000


def load_rows(path):
    with open(path, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    required = {"metric", "this_week", "last_week", "target"}
    if not rows or not required.issubset(rows[0].keys()):
        sys.exit(f"{path}: expected columns {sorted(required)}")
    for i, row in enumerate(rows, start=2):
        for key in required:
            if not (row[key] or "").strip():
                sys.exit(f"{path} line {i}: '{key}' is empty")
        for key in ("this_week", "last_week", "target"):
            float(row[key])  # raises ValueError on a non-numeric cell
    return rows


def build_markdown(rows, week_ending):
    def change(row):
        diff = float(row["this_week"]) - float(row["last_week"])
        return f"{diff:+g}"

    table = ["| Metric | This week | Last week | Change | Target |",
             "|--------|-----------|-----------|--------|--------|"]
    table += [f"| {r['metric']} | {r['this_week']} | {r['last_week']} | {change(r)} | {r['target']} |"
              for r in rows]

    slides = [
        f"# Weekly Operations Report\n\nWeek ending {week_ending}\n\nFigures from weekly_metrics.csv",
        "## Metrics against target\n\n" + "\n".join(table),
        "## Commentary\n\nTO BE WRITTEN BY THE REPORT OWNER BEFORE SHARING\n\nExplain the largest change and any metric below target.",
    ]
    front_matter = '---\ntitle: "Weekly Operations Report"\ntheme: "slate-corporate"\n---\n\n'
    return front_matter + "\n\n---\n\n".join(slides) + "\n", len(slides)


def convert(markdown, fmt):
    key = os.environ.get("SLIDESMATE_API_KEY")
    if not key:
        sys.exit("Set SLIDESMATE_API_KEY (Business plan key from Settings)")
    request = urllib.request.Request(
        API_URL,
        data=json.dumps({"markdown": markdown, "format": fmt}).encode("utf-8"),
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return response.read()
    except urllib.error.HTTPError as error:
        sys.exit(f"SlidesMate API returned HTTP {error.code}: {error.read().decode('utf-8', 'replace')}")


def main():
    csv_path, week_ending = sys.argv[1], sys.argv[2]
    markdown, expected_slides = build_markdown(load_rows(csv_path), week_ending)
    if len(markdown) > MAX_CHARS:
        sys.exit(f"Markdown is {len(markdown)} characters; the API limit is {MAX_CHARS}")

    with open("weekly-report.md", "w", encoding="utf-8") as f:
        f.write(markdown)
    if "--dry-run" in sys.argv:
        print(f"Wrote weekly-report.md ({expected_slides} slides); API call skipped")
        return

    result = json.loads(convert(markdown, "json"))
    if not result.get("success") or result["data"]["slideCount"] != expected_slides:
        sys.exit(f"Unexpected response: {json.dumps(result)[:500]}")
    with open("weekly-report.json", "w", encoding="utf-8") as f:
        json.dump(result, f, indent=2)
    print(f"Converted {expected_slides} slides:", [s["title"] for s in result["data"]["slides"]])

    if "--html" in sys.argv:
        with open("weekly-report.html", "wb") as f:
            f.write(convert(markdown, "html"))
        print("Wrote weekly-report.html")


if __name__ == "__main__":
    main()
