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

Uses only the Python standard library.  Writes cleaned.csv, totals.json,
items.json, medians.json and chart.svg into the current folder.  sales.csv
and rates.csv are only ever read.
"""

import csv
import json
import os
import re
from datetime import datetime

# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------

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

HEADER = ['id', 'date', 'item', 'amount', 'currency', 'edited']

ISO_RE = re.compile(r'^(\d{4})-(\d{1,2})-(\d{1,2})$')
SLASH_RE = re.compile(r'^(\d{1,2})/(\d{1,2})/(\d{4})$')
WORD_RE = re.compile(
    r'^([A-Za-z]+)\s+(\d{1,2})\s*,?\s+(\d{4})$')
WORD_RE2 = re.compile(
    r'^(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})$')


def parse_date(text):
    """Return (year, month, day) or None."""
    if not text:
        return None
    t = text.strip()
    if not t:
        return None

    m = ISO_RE.match(t)
    if m:
        y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
        return _valid(y, mo, d)

    m = SLASH_RE.match(t)
    if m:
        # day/month/year
        d, mo, y = int(m.group(1)), int(m.group(2)), int(m.group(3))
        return _valid(y, mo, d)

    # "March 4, 2026" or "4 March 2026"
    m = WORD_RE.match(t)
    if m:
        mo_name = m.group(1).lower()
        if mo_name in MONTHS:
            return _valid(int(m.group(3)), MONTHS[mo_name], int(m.group(2)))

    m = WORD_RE2.match(t)
    if m:
        mo_name = m.group(2).lower()
        if mo_name in MONTHS:
            return _valid(int(m.group(3)), MONTHS[mo_name], int(m.group(1)))

    return None


def _valid(y, mo, d):
    try:
        datetime(y, mo, d)
    except ValueError:
        return None
    return (y, mo, d)


def parse_amount(text):
    """Return a float or None."""
    if not text:
        return None
    t = text.strip()
    if not t:
        return None

    negative = False
    # brackets -> negative
    if t.startswith('(') and t.endswith(')'):
        negative = True
        t = t[1:-1].strip()

    # strip dollar sign, commas, spaces
    t = t.replace('$', '').replace(',', '').replace(' ', '')

    # strip leading minus
    if t.startswith('-'):
        negative = True
        t = t[1:].strip()

    # must look like a plain number now
    if not t:
        return None
    try:
        val = float(t)
    except ValueError:
        return None

    if negative:
        val = -val
    return val


def parse_edited(text):
    """Return a datetime or None."""
    if not text:
        return None
    t = text.strip()
    if not t:
        return None
    for fmt in ('%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S'):
        try:
            return datetime.strptime(t, fmt)
        except ValueError:
            pass
    return None


def round_half_up(value):
    """Round to two decimals, rounding .005 up (12.345 -> 12.35)."""
    import decimal
    d = decimal.Decimal(str(value))
    return float(d.quantize(decimal.Decimal('0.01'), rounding=decimal.ROUND_HALF_UP))


# --------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------

def main():
    # ---- read rates ----
    rates = {}
    with open('rates.csv', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            cur = row['currency'].strip().upper()
            rates[cur] = float(row['usd_per_unit'].strip())

    # ---- read sales ----
    records = []  # list of dicts with cleaned fields
    with open('sales.csv', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            # normalise keys (lower, strip)
            normed = {}
            for k, v in row.items():
                if k is None:
                    continue
                normed[k.strip().lower()] = v if v else ''

            # skip repeated header lines
            if normed.get('id', '').strip().lower() == 'id':
                continue

            # Id
            sale_id = normed.get('id', '').strip()
            if not sale_id:
                continue

            # Date
            date_tuple = parse_date(normed.get('date', ''))
            if date_tuple is None:
                continue

            # Item
            item = normed.get('item', '').strip()
            if not item:
                continue

            # Amount
            raw_amount = parse_amount(normed.get('amount', ''))
            if raw_amount is None:
                continue

            # Currency
            currency = normed.get('currency', '').strip().upper()
            if currency not in rates:
                continue

            # Edited
            edited = parse_edited(normed.get('edited', ''))
            if edited is None:
                continue

            # Convert to USD
            usd = round_half_up(raw_amount * rates[currency])

            y, mo, d = date_tuple
            date_str = f'{y:04d}-{mo:02d}-{d:02d}'

            records.append({
                'id': sale_id,
                'date': date_str,
                'item': item,
                'amount': usd,
                'edited': edited,
            })

    # ---- deduplicate by Id, keep latest Edited ----
    best = {}  # id -> record
    for rec in records:
        sid = rec['id']
        if sid not in best or rec['edited'] > best[sid]['edited']:
            best[sid] = rec

    cleaned = sorted(best.values(), key=lambda r: (r['date'], r['item']))

    # ---- cleaned.csv ----
    with open('cleaned.csv', 'w', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(['date', 'item', 'amount'])
        for rec in cleaned:
            w.writerow([rec['date'], rec['item'], f"{rec['amount']:.2f}"])

    # ---- totals.json ----
    monthly = {}
    for rec in cleaned:
        month_key = rec['date'][:7]  # YYYY-MM
        monthly.setdefault(month_key, 0.0)
        monthly[month_key] += rec['amount']

    totals = {k: round_half_up(v) for k, v in sorted(monthly.items())}
    with open('totals.json', 'w', encoding='utf-8') as f:
        json.dump(totals, f, indent=2)

    # ---- items.json ----
    item_totals = {}
    for rec in cleaned:
        item_totals.setdefault(rec['item'], 0.0)
        item_totals[rec['item']] += rec['amount']

    items_list = [
        {'item': name, 'total': round_half_up(total)}
        for name, total in item_totals.items()
    ]
    items_list.sort(key=lambda x: (-x['total'], x['item']))
    with open('items.json', 'w', encoding='utf-8') as f:
        json.dump(items_list, f, indent=2)

    # ---- medians.json ----
    month_amounts = {}
    for rec in cleaned:
        month_amounts.setdefault(rec['date'][:7], []).append(rec['amount'])

    medians = {}
    for mk in sorted(month_amounts):
        amounts = sorted(month_amounts[mk])
        n = len(amounts)
        if n % 2 == 1:
            med = amounts[n // 2]
        else:
            med = (amounts[n // 2 - 1] + amounts[n // 2]) / 2.0
        medians[mk] = round_half_up(med)

    with open('medians.json', 'w', encoding='utf-8') as f:
        json.dump(medians, f, indent=2)

    # ---- chart.svg ----
    months_sorted = sorted(monthly.keys())
    if months_sorted:
        max_total = max(totals[m] for m in months_sorted)
    else:
        max_total = 1.0

    # SVG layout constants
    margin_left = 80
    margin_right = 40
    margin_top = 60
    margin_bottom = 80
    bar_width = 60
    bar_gap = 20
    chart_height = 400

    n_bars = len(months_sorted)
    chart_width = margin_left + n_bars * (bar_width + bar_gap) + margin_right
    total_height = margin_top + chart_height + margin_bottom
    total_width = max(chart_width, 400)

    lines = []
    lines.append('<?xml version="1.0" encoding="UTF-8"?>')
    lines.append(f'<svg xmlns="http://www.w3.org/2000/svg" '
                 f'width="{total_width}" height="{total_height}" '
                 f'viewBox="0 0 {total_width} {total_height}">')
    lines.append(f'  <title>Monthly Totals (USD)</title>')
    lines.append(f'  <rect width="{total_width}" height="{total_height}" '
                 f'fill="white"/>')

    for i, mk in enumerate(months_sorted):
        val = totals[mk]
        bar_h = (val / max_total) * chart_height if max_total > 0 else 0
        x = margin_left + i * (bar_width + bar_gap)
        y = margin_top + chart_height - bar_h

        lines.append(f'  <rect class="bar" x="{x:.1f}" '
                     f'y="{y:.1f}" width="{bar_width}" '
                     f'height="{bar_h:.1f}" fill="#4a90d9"/>')

        # label below bar
        label_x = x + bar_width / 2
        label_y = margin_top + chart_height + 20
        lines.append(f'  <text x="{label_x:.1f}" y="{label_y:.1f}" '
                     f'text-anchor="middle" font-size="12" '
                     f'font-family="sans-serif">{mk}</text>')

    lines.append('</svg>')

    with open('chart.svg', 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines) + '\n')


if __name__ == '__main__':
    main()
