#!/usr/bin/env python3
"""clean.py — tidy sales.csv and draw a monthly bar chart.

Reads sales.csv and rates.csv from the current folder and writes
cleaned.csv, totals.json, items.json, medians.json and chart.svg.
Uses only the Python standard library and never modifies the inputs.
"""

import csv
import datetime
import json
import math
import re

MONTHS = {
    "january": 1, "february": 2, "march": 3, "april": 4, "may": 5, "june": 6,
    "july": 7, "august": 8, "september": 9, "october": 10, "november": 11,
    "december": 12,
    "jan": 1, "feb": 2, "mar": 3, "apr": 4, "jun": 6, "jul": 7, "aug": 8,
    "sep": 9, "sept": 9, "oct": 10, "nov": 11, "dec": 12,
}

HEADER = ["Id", "Date", "Item", "Amount", "Currency", "Edited", "Notes"]

CHART_WIDTH = 900
CHART_HEIGHT = 480
MARGIN_LEFT = 80
MARGIN_RIGHT = 40
MARGIN_TOP = 70
MARGIN_BOTTOM = 60


def parse_date(text):
    """Return a datetime.date, or None when text holds no usable date."""
    if text is None:
        return None
    value = text.strip()
    if not value:
        return None

    iso = re.match(r"^(\d{4})-(\d{1,2})-(\d{1,2})$", value)
    if iso:
        try:
            return datetime.date(int(iso.group(1)), int(iso.group(2)),
                                 int(iso.group(3)))
        except ValueError:
            return None

    slashed = re.match(r"^(\d{1,2})/(\d{1,2})/(\d{4})$", value)
    if slashed:
        # Slashed dates are always day/month/year.
        try:
            return datetime.date(int(slashed.group(3)), int(slashed.group(2)),
                                 int(slashed.group(1)))
        except ValueError:
            return None

    long_first = re.match(r"^([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})$", value)
    if long_first:
        month = MONTHS.get(long_first.group(1).lower())
        if month:
            try:
                return datetime.date(int(long_first.group(3)), month,
                                     int(long_first.group(2)))
            except ValueError:
                return None

    short_first = re.match(r"^(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})$", value)
    if short_first:
        month = MONTHS.get(short_first.group(2).lower())
        if month:
            try:
                return datetime.date(int(short_first.group(3)), month,
                                     int(short_first.group(1)))
            except ValueError:
                return None

    return None


def parse_edited(text):
    """Return a datetime.datetime, or None when text holds no usable stamp."""
    if text is None:
        return None
    value = text.strip()
    if not value:
        return None
    for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S"):
        try:
            return datetime.datetime.strptime(value, fmt)
        except ValueError:
            continue
    return None


def parse_amount(text):
    """Return a float, or None when text is not a number.

    Handles a dollar sign, thousands separators, surrounding space and
    refunds written with a minus sign or in brackets.
    """
    if text is None:
        return None
    value = text.strip()
    if not value:
        return None

    negative = False
    bracketed = re.match(r"^\((.*)\)$", value)
    if bracketed:
        negative = True
        value = bracketed.group(1).strip()

    value = value.lstrip("$").strip()
    if not value:
        return None

    if not re.match(r"^\s*-?[\d,]*\.?\d*\s*$", value):
        return None

    value = value.replace(",", "").strip()
    if not re.match(r"^-?\d*\.?\d*$", value):
        return None

    try:
        amount = float(value)
    except ValueError:
        return None

    if negative:
        amount = -amount
    return amount


def round_half_up(value):
    """Round to two decimals, sending exact half cents up."""
    return math.floor(value * 100.0 + 0.5) / 100.0


def read_rates(path):
    rates = {}
    with open(path, newline="", encoding="utf-8-sig") as handle:
        for row in csv.DictReader(handle):
            if not row:
                continue
            code = (row.get("currency") or "").strip().upper()
            if not code:
                continue
            try:
                rate = float((row.get("usd_per_unit") or "").strip())
            except (ValueError, AttributeError):
                continue
            rates[code] = rate
    return rates


def read_rows(path, rates):
    """Read sales.csv, dropping blank lines, repeated headers and bad rows."""
    rows = []
    with open(path, newline="", encoding="utf-8-sig") as handle:
        for raw in csv.reader(handle):
            if not raw or all(not field.strip() for field in raw):
                continue
            fields = [field.strip() for field in raw] + [""] * (
                len(HEADER) - len(raw))
            if [field.lower() for field in fields[:len(HEADER)]] == HEADER:
                continue

            sale_id = fields[0].strip()
            if not sale_id:
                continue

            date = parse_date(fields[1])
            item = fields[2].strip()
            amount = parse_amount(fields[3])
            currency = fields[4].strip().upper()
            edited = parse_edited(fields[5])

            if date is None or amount is None or edited is None:
                continue
            if not item:
                continue
            if currency not in rates:
                continue

            rows.append({
                "id": sale_id,
                "date": date,
                "item": item,
                "amount": amount,
                "currency": currency,
                "edited": edited,
            })
    return rows


def dedupe(rows):
    """Keep one row per Id: the one with the latest Edited time."""
    latest = {}
    for row in rows:
        current = latest.get(row["id"])
        if current is None or row["edited"] > current["edited"]:
            latest[row["id"]] = row
    return list(latest.values())


def median(values):
    ordered = sorted(values)
    count = len(ordered)
    if count == 0:
        return 0.0
    middle = count // 2
    if count % 2 == 1:
        return ordered[middle]
    return (ordered[middle - 1] + ordered[middle]) / 2.0


def fmt_amount(value):
    if value < 0:
        return "-%.2f" % abs(value)
    return "%.2f" % value


def build_chart(months, totals):
    plot_width = CHART_WIDTH - MARGIN_LEFT - MARGIN_RIGHT
    plot_height = CHART_HEIGHT - MARGIN_TOP - MARGIN_BOTTOM
    peak = max(totals.values())
    if peak <= 0:
        peak = 1.0

    slot = plot_width / len(months)
    bar_width = slot * 0.6

    parts = [
        '<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" '
        'viewBox="0 0 %d %d">' % (CHART_WIDTH, CHART_HEIGHT, CHART_WIDTH,
                                  CHART_HEIGHT),
        '<title>Monthly sales totals in US dollars</title>',
        '<rect x="0" y="0" width="%d" height="%d" fill="#ffffff"/>'
        % (CHART_WIDTH, CHART_HEIGHT),
    ]

    for index, month in enumerate(months):
        total = totals[month]
        height = plot_height * (total / peak)
        x = MARGIN_LEFT + slot * index + (slot - bar_width) / 2
        y = MARGIN_TOP + plot_height - height
        parts.append(
            '<rect class="bar" x="%.2f" y="%.2f" width="%.2f" height="%.2f" '
            'fill="#4a7fbf"/>' % (x, y, bar_width, height))
        label_x = MARGIN_LEFT + slot * index + slot / 2
        parts.append(
            '<text x="%.2f" y="%d" text-anchor="middle" '
            'font-size="14" fill="#333333">%s</text>'
            % (label_x, MARGIN_TOP + plot_height + 28, month))

    parts.append("</svg>")
    return "\n".join(parts)


def main():
    rates = read_rates("rates.csv")
    rows = dedupe(read_rows("sales.csv", rates))

    cleaned = []
    for row in rows:
        rate = rates[row["currency"]]
        cleaned.append({
            "date": row["date"],
            "item": row["item"],
            "amount": round_half_up(row["amount"] * rate),
        })

    cleaned.sort(key=lambda row: (row["date"], row["item"]))

    with open("cleaned.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["date", "item", "amount"])
        for row in cleaned:
            writer.writerow([row["date"].isoformat(), row["item"],
                             fmt_amount(row["amount"])])

    months = sorted({row["date"].strftime("%Y-%m") for row in cleaned})

    month_totals = {month: 0.0 for month in months}
    for row in cleaned:
        month_totals[row["date"].strftime("%Y-%m")] += row["amount"]
    totals = {month: round_half_up(month_totals[month]) for month in months}

    with open("totals.json", "w", encoding="utf-8") as handle:
        json.dump(totals, handle, indent=2)
        handle.write("\n")

    item_totals = {}
    for row in cleaned:
        item_totals[row["item"]] = item_totals.get(row["item"], 0.0) + row["amount"]
    items = [{"item": name, "total": round_half_up(total)}
             for name, total in item_totals.items()]
    items.sort(key=lambda entry: (-entry["total"], entry["item"]))

    with open("items.json", "w", encoding="utf-8") as handle:
        json.dump(items, handle, indent=2)
        handle.write("\n")

    month_amounts = {month: [] for month in months}
    for row in cleaned:
        month_amounts[row["date"].strftime("%Y-%m")].append(row["amount"])
    medians = {month: round_half_up(median(month_amounts[month]))
               for month in months}

    with open("medians.json", "w", encoding="utf-8") as handle:
        json.dump(medians, handle, indent=2)
        handle.write("\n")

    with open("chart.svg", "w", encoding="utf-8") as handle:
        handle.write(build_chart(months, totals))
        handle.write("\n")


if __name__ == "__main__":
    main()
