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

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

def parse_date(date_str):
    date_str = date_str.strip()
    
    # Format: YYYY-MM-DD
    if re.match(r'^\d{4}-\d{2}-\d{2}$', date_str):
        return datetime.strptime(date_str, '%Y-%m-%d').date()
    
    # Format: March 4, 2026
    if re.match(r'^[A-Za-z]+ \d+, \d{4}$', date_str):
        return datetime.strptime(date_str, '%B %d, %Y').date()
    
    # Format: 4 Mar 2026
    if re.match(r'^\d+ [A-Za-z]+ \d{4}$', date_str):
        return datetime.strptime(date_str, '%d %b %Y').date()
    
    # Format: DD/MM/YYYY or MM/DD/YYYY - always day/month/year per instructions
    if re.match(r'^\d{2}/\d{2}/\d{4}$', date_str):
        parts = date_str.split('/')
        day = int(parts[0])
        month = int(parts[1])
        year = int(parts[2])
        return datetime(year, month, day).date()
    
    return None

def parse_amount(amount_str):
    amount_str = amount_str.strip()
    
    # Check for negative indicators: brackets or minus sign
    is_negative = False
    if amount_str.startswith('(') and amount_str.endswith(')'):
        is_negative = True
        amount_str = amount_str[1:-1].strip()
    elif amount_str.startswith('-'):
        is_negative = True
        amount_str = amount_str[1:].strip()
    elif amount_str.startswith('$') and amount_str[1:].strip().startswith('-'):
        # ($-45.00) unlikely, but ($45.00) with minus inside? No, ($45.00) is handled above
        pass
    
    # Remove dollar sign
    if amount_str.startswith('$'):
        amount_str = amount_str[1:]
    
    # Remove spaces and commas
    amount_str = amount_str.replace(' ', '').replace(',', '')
    
    try:
        value = float(amount_str)
    except ValueError:
        return None
    
    if is_negative:
        value = -value
    
    return value

def parse_edited_time(edited_str):
    edited_str = edited_str.strip()
    # Format: YYYY-MM-DD HH:MM (hours can be 1 or 2 digits)
    # e.g., 2026-03-04 14:05 or 2026-03-04 9:05
    try:
        return datetime.strptime(edited_str, '%Y-%m-%d %H:%M')
    except ValueError:
        try:
            return datetime.strptime(edited_str, '%Y-%m-%d %d:%M')
        except ValueError:
            return None

def main():
    rates = read_rates('rates.csv')
    
    # Read sales.csv
    rows = []
    with open('sales.csv', 'r', newline='') as f:
        reader = csv.DictReader(f)
        for row in reader:
            # Skip blank lines or lines that don't have required fields
            # Check if it's a repeated header
            if row.get('Id') == 'Id' and row.get('Date') == 'Date':
                continue
            
            rows.append(row)
    
    # Clean and filter rows
    cleaned_rows = []
    for row in rows:
        # Get fields
        item_id = row.get('Id', '').strip()
        date_str = row.get('Date', '').strip()
        item = row.get('Item', '').strip()
        amount_str = row.get('Amount', '').strip()
        currency_str = row.get('Currency', '').strip()
        edited_str = row.get('Edited', '').strip()
        notes = row.get('Notes', '')
        
        # Skip if no date
        if not date_str:
            continue
        
        # Parse date
        parsed_date = parse_date(date_str)
        if parsed_date is None:
            continue
        
        # Skip if no item
        if not item:
            continue
        
        # Skip if no amount
        if not amount_str:
            continue
        
        # Parse amount
        parsed_amount = parse_amount(amount_str)
        if parsed_amount is None:
            continue
        
        # Get currency
        currency = currency_str.upper().replace(' ', '')
        if currency not in rates:
            continue
        
        # Convert amount to USD
        usd_amount = parsed_amount * rates[currency]
        # Round to nearest cent
        usd_amount = round(usd_amount, 2)
        
        # Parse edited time
        parsed_edited = parse_edited_time(edited_str)
        if parsed_edited is None:
            continue
        
        # Clean item name: remove spaces before or after
        # "Remove those spaces but otherwise keep the name as written"
        # So strip the item name
        item_clean = item.strip()
        
        cleaned_rows.append({
            'id': item_id,
            'date': parsed_date,
            'item': item_clean,
            'amount': usd_amount,
            'edited': parsed_edited
        })
    
    # Deduplicate by Id: keep the one with the latest Edited time
    # If same Edited time, keep one of them
    id_rows = defaultdict(list)
    for row in cleaned_rows:
        id_rows[row['id']].append(row)
    
    final_rows = []
    for id_key, id_list in id_rows.items():
        # Sort by edited time descending, then keep the first
        id_list.sort(key=lambda x: x['edited'], reverse=True)
        final_rows.append(id_list[0])
    
    # Sort by date, then by item
    final_rows.sort(key=lambda x: (x['date'], x['item']))
    
    # Write cleaned.csv
    with open('cleaned.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['date', 'item', 'amount'])
        for row in final_rows:
            date_str = row['date'].strftime('%Y-%m-%d')
            item = row['item']
            amount = row['amount']
            # Format amount with exactly two decimals, no dollar sign, no commas
            amount_str = f"{amount:.2f}"
            writer.writerow([date_str, item, amount_str])
    
    # Calculate monthly totals for totals.json
    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_dict = {}
    for month_key in sorted(monthly_totals.keys()):
        totals_dict[month_key] = round(monthly_totals[month_key], 2)
    
    # Write totals.json
    with open('totals.json', 'w') as f:
        json.dump(totals_dict, f)
    
    # Calculate item totals for items.json
    item_totals = defaultdict(float)
    for row in final_rows:
        item_totals[row['item']] += row['amount']
    
    # Round item totals to two decimals
    items_list = []
    for item_name, total in item_totals.items():
        items_list.append({"item": item_name, "total": round(total, 2)})
    
    # Sort by total descending, then by name
    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 monthly medians for medians.json
    monthly_amounts = defaultdict(list)
    for row in final_rows:
        month_key = row['date'].strftime('%Y-%m')
        monthly_amounts[month_key].append(row['amount'])
    
    medians_dict = {}
    for month_key in sorted(monthly_amounts.keys()):
        amounts = sorted(monthly_amounts[month_key])
        n = len(amounts)
        if n % 2 == 1:
            median = amounts[n // 2]
        else:
            # Even number: halfway between two middle amounts
            mid1 = amounts[n // 2 - 1]
            mid2 = amounts[n // 2]
            median = (mid1 + mid2) / 2
            # If that lands on half a cent, round it up
            # Half a cent means the third decimal is 5
            # Check if median is X.XX5 -> round up to X.XX + 0.01
            # Actually, the instruction says: "if that lands on half a cent, round it up (12.345 becomes 12.35)"
            # So we need to round to 2 decimals, but with a special rule for .XX5
            # Standard rounding rounds .XX5 to .XX (round half to even) or .XX+0.01 (round half up)
            # The example says 12.345 becomes 12.35, which is round half up.
            # So we should use round half up for the median.
            # But wait, the instruction says "round it up (12.345 becomes 12.35)"
            # So if the median is exactly X.XX5, we round up.
            # For other cases, we round to 2 decimals normally.
            # Let's implement a custom rounding function.
            pass
        
        # Custom rounding: round to 2 decimals, but if the third decimal is 5, round up
        # Actually, the instruction only mentions "half a cent", which is 0.005
        # So if the median is 12.345, it becomes 12.35
        # If the median is 12.344, it becomes 12.34
        # If the median is 12.346, it becomes 12.35
        # So standard rounding to 2 decimals should work, except for the .XX5 case
        # Standard round() in Python uses round half to even
        # So 12.345 would round to 12.34 (since 4 is even)
        # But we want 12.35
        # So we need to implement round half up
        
        def round_half_up(val, decimals):
            multiplier = 10 ** decimals
            return math.floor(val * multiplier + 0.5) / multiplier
        
        median = round_half_up(median, 2)
        medians_dict[month_key] = median
    
    # Write medians.json
    with open('medians.json', 'w') as f:
        json.dump(medians_dict, f)
    
    # Generate chart.svg
    # Bar chart of monthly totals
    # Title element, rect elements with class="bar", text elements for labels
    # Bar heights proportional to totals
    
    # Get all months and their totals
    months_sorted = sorted(totals_dict.keys())
    if not months_sorted:
        # Handle empty case
        svg_content = '<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"></svg>'
        with open('chart.svg', 'w') as f:
            f.write(svg_content)
        return
    
    max_total = max(totals_dict.values())
    min_total = min(totals_dict.values())
    
    # Chart dimensions
    width = 800
    height = 400
    margin_left = 60
    margin_right = 20
    margin_top = 60
    margin_bottom = 80
    
    chart_width = width - margin_left - margin_right
    chart_height = height - margin_top - margin_bottom
    
    # Calculate bar width and spacing
    num_months = len(months_sorted)
    bar_width = chart_width / num_months * 0.8
    bar_spacing = chart_width / num_months * 0.2
    
    # Generate SVG
    svg_lines = []
    svg_lines.append('<?xml version="1.0" encoding="UTF-8"?>')
    svg_lines.append(f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}">')
    
    # Title
    svg_lines.append(f'<text x="{width/2}" y="30" text-anchor="middle" font-size="16">Monthly Totals</text>')
    
    # Bars and labels
    for i, month in enumerate(months_sorted):
        total = totals_dict[month]
        
        # Bar height proportional to total
        if max_total > 0:
            bar_height = (total / max_total) * chart_height
        else:
            bar_height = 0
        
        x = margin_left + i * (bar_width + bar_spacing) + bar_spacing / 2
        y = margin_top + chart_height - bar_height
        
        # Rect element
        svg_lines.append(f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" class="bar" fill="blue"/>')
        
        # Label
        label_x = x + bar_width / 2
        label_y = margin_top + chart_height + 20
        svg_lines.append(f'<text x="{label_x}" y="{label_y}" text-anchor="middle" font-size="12">{month}</text>')
    
    # Close SVG
    svg_lines.append('</svg>')
    
    svg_content = '\n'.join(svg_lines)
    
    with open('chart.svg', 'w') as f:
        f.write(svg_content)

if __name__ == '__main__':
    main()
