import csv
import json
import math
import re
import os
from datetime import datetime
from collections import defaultdict

def load_rates(filename):
    rates = {}
    with open(filename, 'r', newline='') as f:
        reader = csv.DictReader(f)
        for row in reader:
            currency = row['currency'].strip().upper()
            rate = float(row['usd_per_unit'])
            rates[currency] = rate
    return rates

def parse_date(date_str):
    date_str = date_str.strip()
    
    # Format 1: 2026-03-04
    try:
        dt = datetime.strptime(date_str, '%Y-%m-%d')
        return dt
    except ValueError:
        pass
    
    # Format 2: March 4, 2026
    try:
        dt = datetime.strptime(date_str, '%B %d, %Y')
        return dt
    except ValueError:
        pass
    
    # Format 3: 4 Mar 2026
    try:
        dt = datetime.strptime(date_str, '%d %b %Y')
        return dt
    except ValueError:
        pass
    
    # Format 4: 04/03/2026 (DD/MM/YYYY)
    try:
        parts = date_str.split('/')
        if len(parts) == 3:
            day = int(parts[0])
            month = int(parts[1])
            year = int(parts[2])
            dt = datetime(year, month, day)
            return dt
    except ValueError:
        pass
    
    return None

def parse_amount(amount_str, currency, rates):
    if not amount_str or not amount_str.strip():
        return None
    
    amount_str = amount_str.strip()
    
    # Check for negative indicators
    is_negative = False
    
    # Check for brackets: (45.00) or ($45.00)
    if amount_str.startswith('(') and amount_str.endswith(')'):
        is_negative = True
        amount_str = amount_str[1:-1].strip()
    
    # Check for minus sign
    if amount_str.startswith('-'):
        is_negative = True
        amount_str = amount_str[1:].strip()
    
    # Check for minus sign in brackets like (-45.00)
    if amount_str.startswith('(') and amount_str.endswith(')') and amount_str.startswith('(') and 'negative' not in locals():
        # Already handled above
    
    # Remove dollar sign and commas
    amount_str = amount_str.replace('$', '').replace(',', '').strip()
    
    # Remove spaces
    amount_str = amount_str.strip()
    
    # Try to parse the number
    try:
        value = float(amount_str)
    except ValueError:
        return None
    
    if is_negative:
        value = -abs(value)
    
    # Convert to USD
    currency = currency.strip().upper()
    if currency not in rates:
        return None
    
    usd_value = value * rates[currency]
    
    # Round to nearest cent
    usd_value = round(usd_value, 2)
    
    return usd_value

def clean_sales():
    rates = load_rates('rates.csv')
    
    # Read sales.csv
    rows = []
    with open('sales.csv', 'r', newline='') as f:
        reader = csv.DictReader(f)
        for row in reader:
            rows.append(row)
    
    # Process each row
    cleaned_rows = []
    
    for row in rows:
        # Check for header repetition
        if row.get('Id') == 'Id' and row.get('Date') == 'Date':
            continue
        
        # Get Id
        sale_id = row.get('Id', '').strip()
        if not sale_id:
            continue
        
        # Get Date
        date_str = row.get('Date', '').strip()
        if not date_str:
            continue
        
        parsed_date = parse_date(date_str)
        if parsed_date is None:
            continue
        
        # Get Item
        item = row.get('Item', '').strip()
        if not item:
            continue
        
        # Get Amount
        amount_str = row.get('Amount', '').strip()
        if not amount_str:
            continue
        
        currency = row.get('Currency', '').strip()
        if not currency:
            continue
        
        usd_amount = parse_amount(amount_str, currency, rates)
        if usd_amount is None:
            continue
        
        # Get Edited
        edited_str = row.get('Edited', '').strip()
        if not edited_str:
            continue
        
        try:
            edited_dt = datetime.strptime(edited_str, '%Y-%m-%d %H:%M')
        except ValueError:
            # Try with single digit hour
            try:
                # Format like 2026-03-04 9:05
                edited_dt = datetime.strptime(edited_str, '%Y-%m-%d %H:%M')
            except ValueError:
                continue
        
        cleaned_rows.append({
            'id': sale_id,
            'date': parsed_date,
            'item': item,
            'amount': usd_amount,
            'edited': edited_dt
        })
    
    # Deduplicate by Id: keep the one with the latest Edited time
    # If same Edited time, keep one of them
    id_to_row = {}
    for row in cleaned_rows:
        sale_id = row['id']
        if sale_id not in id_to_row:
            id_to_row[sale_id] = row
        else:
            existing_row = id_to_row[sale_id]
            if row['edited'] > existing_row['edited']:
                id_to_row[sale_id] = row
    
    # Create final list
    final_rows = list(id_to_row.values())
    
    # Sort by date, then by item
    final_rows.sort(key=lambda r: (r['date'], r['item']))
    
    # Write cleaned.csv
    with open('cleaned.csv', 'w', newline='') as f:
        f.write('date,item,amount\n')
        for row in final_rows:
            date_str = row['date'].strftime('%Y-%m-%d')
            item = row['item']
            amount = f"{row['amount']:.2f}"
            f.write(f'{date_str},{item},{amount}\n')
    
    # Calculate totals by month
    monthly_totals = defaultdict(float)
    for row in final_rows:
        month_key = row['date'].strftime('%Y-%m')
        monthly_totals[month_key] += row['amount']
    
    # Round monthly totals to two decimals
    totals_json = {}
    for month in sorted(monthly_totals.keys()):
        totals_json[month] = round(monthly_totals[month], 2)
    
    # Write totals.json
    with open('totals.json', 'w') as f:
        json.dump(totals_json, f)
    
    # Calculate totals by item
    item_totals = defaultdict(float)
    for row in final_rows:
        item_totals[row['item']] += row['amount']
    
    # Sort by total descending, then by name
    items_list = []
    for item, total in item_totals.items():
        items_list.append({'item': item, 'total': round(total, 2)})
    
    items_list.sort(key=lambda x: (-x['total'], x['item']))
    
    # Write items.json
    with open('items.json', 'w') as f:
        json.dump(items_list, f)
    
    # Calculate medians by month
    monthly_amounts = defaultdict(list)
    for row in final_rows:
        month_key = row['date'].strftime('%Y-%m')
        monthly_amounts[month_key].append(row['amount'])
    
    medians_json = {}
    for month in sorted(monthly_amounts.keys()):
        amounts = sorted(monthly_amounts[month])
        n = len(amounts)
        if n % 2 == 1:
            median = amounts[n // 2]
        else:
            mid1 = amounts[n // 2 - 1]
            mid2 = amounts[n // 2]
            median = (mid1 + mid2) / 2
            # If it lands on half a cent, round up
            # Check if the third decimal is 5 and we need to round up
            # Actually, the instruction says: "if that lands on half a cent, round it up (12.345 becomes 12.35)"
            # So we round to 2 decimals, but if the third decimal is 5, we round up (away from zero for positive, towards zero for negative? No, standard rounding)
            # Let's use standard rounding to 2 decimals
            median = round(median, 2)
            # But wait, the example says 12.345 becomes 12.35. That's standard rounding (round half up).
            # Python's round uses round half to even. So we need to implement round half up.
            # Let's implement round half up manually.
        
        # Implement round half up
        median = round_half_up(median, 2)
        medians_json[month] = median
    
    # Write medians.json
    with open('medians.json', 'w') as f:
        json.dump(medians_json, f)
    
    # Draw chart.svg
    draw_chart(totals_json)

def round_half_up(value, decimals):
    # Round to specified decimals, using round half up
    multiplier = 10 ** decimals
    shifted = value * multiplier
    # Check if the fractional part is exactly 0.5
    # Actually, let's just use the standard approach for round half up
    import decimal
    d = decimal.Decimal(str(value))
    if decimals == 0:
        rounded = d.quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
    else:
        rounded = d.quantize(decimal.Decimal('0.' + '0' * (decimals - 1) + '1'), rounding=decimal.ROUND_HALF_UP)
    return float(rounded)

def draw_chart(monthly_totals):
    # Get sorted months
    months = sorted(monthly_totals.keys())
    totals = [monthly_totals[m] for m in months]
    
    # Find max total for scaling
    max_total = max(abs(t) for t in totals) if totals else 1
    if max_total == 0:
        max_total = 1
    
    # SVG dimensions
    width = 800
    height = 400
    margin_top = 50
    margin_bottom = 50
    margin_left = 100
    margin_right = 50
    
    # Bar width
    bar_width = 40
    bar_gap = 20
    
    # Calculate bar heights
    max_height = height - margin_top - margin_bottom
    bar_heights = []
    for t in totals:
        if max_total == 0:
            bar_heights.append(0)
        else:
            bar_heights.append(abs(t) / max_total * max_height)
    
    # SVG content
    svg = f'''<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}">
  <title>Monthly Sales Totals</title>
'''
    
    # Draw bars
    for i, month in enumerate(months):
        x = margin_left + i * (bar_width + bar_gap)
        # For positive totals, bar goes down from margin_top
        # For negative totals, bar goes up from margin_top + max_height
        # But all totals should be positive since we're summing amounts
        # Actually, refunds are negative, so totals can be negative
        # Let's handle both positive and negative
        
        h = bar_heights[i]
        if totals[i] >= 0:
            y = margin_top + max_height - h
            height_val = h
        else:
            y = margin_top + max_height
            height_val = h
        
        svg += f'  <rect x="{x}" y="{y}" width="{bar_width}" height="{height_val}" class="bar" fill="blue"/>\n'
        
        # Label
        label_x = x + bar_width / 2
        label_y = margin_top + max_height + 15
        svg += f'  <text x="{label_x}" y="{label_y}" text-anchor="middle" font-size="12">{month}</text>\n'
    
    svg += '</svg>'
    
    with open('chart.svg', 'w') as f:
        f.write(svg)

if __name__ == '__main__':
    clean_sales()
