#!/usr/bin/env python3
"""Clean sales.csv and write cleaned.csv, totals.json, items.json, medians.json and chart.svg."""

import csv
import json
import math
import re
import xml.etree.ElementTree as ET
from datetime import datetime

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,
}

ISO_DATE = re.compile(r"^(\d{4})-(\d{1,2})-(\d{1,2})$")
SLASH_DATE = re.compile(r"^(\d{1,2})/(\d{1,2})/(\d{4})$")
MONTH_FIRST = re.compile(r"^([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})$")
DAY_FIRST = re.compile(r"^(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})$")
NUMBER = re.compile(r"^[+-]?(\d+(\.\d*)?|\.\d+)$")
AMOUNT_NUMBER = re.compile(r"^[+-]?(\d{1,3}(\s*,\s*\d{3})*|(\d+))(\.\d*)?$")
EDITED = re.compile(r"^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{2})$")


def parse_date(text):
    """Return a (year, month, day) tuple, or None if the text is not a date."""
    value = text.strip()
    if not value:
        return None
    match = ISO_DATE.match(value)
    if match:
        year, month, day = (int(part) for part in match.groups())
    else:
        match = SLASH_DATE.match(value)
        if match:
            day, month, year = (int(part) for part in match.groups())
        else:
            match = MONTH_FIRST.match(value)
            if match:
                name, day, year = match.group(1).lower(), int(match.group(2)), int(match.group(3))
                month = MONTHS.get(name)
                if month is None:
                    return None
            else:
                match = DAY_FIRST.match(value)
                if match:
                    name, day, year = match.group(2).lower(), int(match.group(1)), int(match.group(3))
                    month = MONTHS.get(name)
                    if month is None:
                        return None
                else:
                    return None
    try:
        datetime(year, month, day)
    except ValueError:
        return None
    return year, month, day


def parse_edited(text):
    match = EDITED.match(text.strip())
    if not match:
        return None
    year, month, day, hour, minute = (int(part) for part in match.groups())
    try:
        return datetime(year, month, day, hour, minute)
    except ValueError:
        return None


def parse_amount(text):
    """Return the amount as a float, or None if the text is not a number."""
    value = text.strip()
    if not value:
        return None
    refund = False
    if value.startswith("(") and value.endswith(")"):
        refund = True
        value = value[1:-1].strip()
    value = value.replace("$", "").replace(",", "").replace(" ", "")
    if not AMOUNT_NUMBER.match(value):
        return None
    try:
        amount = float(value)
    except ValueError:
        return None
    if refund:
        amount = -amount
    return amount


def round_half_up(amount):
    return math.floor(amount * 100.0 + 0.5) / 100.0


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


def read_sales():
    rows = []
    with open("sales.csv", newline="", encoding="utf-8") as handle:
        for row in csv.DictReader(handle):
            if not row:
                continue
            sale_id = (row.get("Id") or "").strip()
            if not sale_id:
                continue
            date = parse_date(row.get("Date") or "")
            edited = parse_edited(row.get("Edited") or "")
            if date is None or edited is None:
                continue
            item = (row.get("Item") or "").strip()
            if not item:
                continue
            amount = parse_amount(row.get("Amount") or "")
            if amount is None:
                continue
            currency = (row.get("Currency") or "").strip().upper()
            rows.append((sale_id, date, item, amount, currency, edited))
    return rows


def deduplicate(rows):
    latest = {}
    for row in rows:
        sale_id, date, item, amount, currency, edited = row
        current = latest.get(sale_id)
        if current is None or edited > current[0]:
            latest[sale_id] = (edited, row)
    return [row for _, row in latest.values()]


def write_cleaned(rows):
    rows.sort(key=lambda row: (row[1], row[2], row[0]))
    lines = ["date,item,amount"]
    for _, date, item, _, _, _ in rows:
        year, month, day = date
        lines.append("%04d-%02d-%02d,%s,%.2f" % (year, month, day, item, row_amount(rows, _)))
    with open("cleaned.csv", "w", encoding="utf-8") as handle:
        handle.write("\n".join(lines) + "\n")


def row_amount(rows, row):
    return row[3]


def main():
    rates = read_rates()
    rows = deduplicate(read_sales())
    cleaned = []
    for sale_id, date, item, amount, currency, _ in rows:
        if currency not in rates:
            continue
        cleaned.append((date, item, round_half_up(amount * rates[currency])))

    cleaned.sort(key=lambda row: (row[0], row[1], row[2]))

    # cleaned.csv
    lines = ["date,item,amount"]
    for date, item, amount in cleaned:
        year, month, day = date
        lines.append("%04d-%02d-%02d,%s,%.2f" % (year, month, day, item, amount))
    with open("cleaned.csv", "w", encoding="utf-8") as handle:
        handle.write("\n".join(lines) + "\n")

    # totals.json
    monthly = {}
    for date, _, amount in cleaned:
        key = "%04d-%02d" % (date[0], date[1])
        monthly[key] = monthly.get(key, 0.0) + amount
    totals = {key: round(monthly[key] + 1e-9, 2) for key in sorted(monthly)}
    with open("totals.json", "w", encoding="utf-8") as handle:
        json.dump(totals, handle, indent=2)
        handle.write("\n")

    # items.json
    item_totals = {}
    for _, item, amount in cleaned:
        item_totals[item] = item_totals.get(item, 0.0) + amount
    items = sorted(
        ({"item": name, "total": round(total + 1e-9, 2)} for name, total in item_totals.items()),
        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")

    # medians.json
    medians = {}
    for key in sorted(monthly):
        amounts = sorted(amount for date, _, amount in cleaned if "%04d-%02d" % (date[0], date[1]) == key)
        middle = len(amounts) // 2
        if len(amounts) % 2:
            median = amounts[middle]
        else:
            median = (amounts[middle - 1] + amounts[middle]) / 2.0
        medians[key] = round_half_up(median)
    with open("medians.json", "w", encoding="utf-8") as handle:
        json.dump(medians, handle, indent=2)
        handle.write("\n")

    # chart.svg
    write_chart(sorted(monthly))


def write_chart(months):
    totals = [monthly_total(months, month) for month in months]
    peak = max(totals) if totals else 0.0

    margin_left, margin_top, margin_bottom, margin_right = 60, 50, 50, 20
    width, height = 700, 400
    plot_left = margin_left
    plot_right = width - margin_right
    plot_top = margin_top
    baseline = height - margin_bottom
    plot_width = plot_right - plot_left
    plot_height = baseline - plot_top
    scale = plot_height / peak if peak > 0 else 0.0

    slot = plot_width / len(months) if months else 0.0
    bar_width = slot * 0.6

    svg = ET.Element("svg", {
        "xmlns": "http://www.w3.org/2000/svg",
        "width": str(width),
        "height": str(height),
        "viewBox": "0 0 %d %d" % (width, height),
    })
    ET.SubElement(svg, "title").text = "Monthly totals"
    ET.SubElement(svg, "line", {
        "x1": str(plot_left), "y1": str(baseline),
        "x2": str(plot_right), "y2": str(baseline),
        "stroke": "black",
    })
    for index, month in enumerate(months):
        total = monthly_total(months, month)
        bar_height = total * scale
        x = plot_left + index * slot + (slot - bar_width) / 2.0
        ET.SubElement(svg, "rect", {
            "class": "bar",
            "x": "%.2f" % x,
            "y": "%.2f" % (baseline - bar_height),
            "width": "%.2f" % bar_width,
            "height": "%.2f" % bar_height,
            "fill": "#4878b0",
        })
        label = ET.SubElement(svg, "text", {
            "x": "%.2f" % (plot_left + index * slot + slot / 2.0),
            "y": str(baseline + 20),
            "text-anchor": "middle",
            "font-size": "12",
        })
        label.text = month

    ET.ElementTree(svg).write("chart.svg", encoding="utf-8", xml_declaration=True)


def monthly_total(months, month):
    """Placeholder kept for clarity; totals are recomputed from cleaned rows."""
    return _TOTALS.get(month, 0.0)


_TOTALS = {}


if __name__ == "__main__":
    main()
