import csv
import json
import re
import math
import svgwrite
import svgwrite.helpers
from datetime import datetime
from collections import defaultdict

def parse_date(date_str):
    date_str = date_str.strip()
    # Style 1: YYYY-MM-DD
    if re.match(r'^\d{4}-\d{2}-\d{2}$', date_str):
        return datetime.strptime(date_str, '%Y-%m-%d')
    # Style 2: "Month D, YYYY" e.g. "March 4, 2026"
    if re.match(r'^[A-Za-z]+ \d+, \d{4}$', date_str):
        return datetime.strptime(date_str, '%B %d, %Y')
    # Style 3: "D Mon YYYY" e.g. "4 Mar 2026"
    if re.match(r'^\d+ [A-Za-z]+ \d{4}$', date_str):
        return datetime.strptime(date_str, '%d %b %Y')
    # Style 4: "DD/MM/YYYY"
    if re.match(r'^\d{2}/\d{2}/\d{4}$', date_str):
        parts = date_str.split('/')
        return datetime.strptime(date_str, '%d/%m/%Y')
    return None

def parse_amount(amount_str, currency):
    amount_str = amount_str.strip()
    # Remove dollar sign
    amount_str = amount_str.replace('$', '')
    
    # 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]
    elif amount_str.startswith('-'):
        is_negative = True
        amount_str = amount_str[1:]
    
    # Remove commas and spaces
    amount_str = amount_str.replace(',', '').replace(' ', '')
    
    try:
        val = float(amount_str)
    except ValueError:
        return None
    
    if is_negative:
        val = -val
    
    # Convert to USD
    rates = {
        'USD': 1.0000,
        'CAD': 0.7150,
        'EUR': 1.0825,
        'GBP': 1.2650
    }
    
    currency = currency.strip().upper()
    if currency not in rates:
        return None
    
    usd_val = val * rates[currency]
    return usd_val

def load_rates():
    rates = {}
    with open('rates.csv', 'r') as f:
        reader = csv.reader(f)
        header = next(reader)
        for row in reader:
            if len(row) >= 2:
                rates[row[0].strip().upper()] = float(row[1].strip())
    return rates

def main():
    rates = load_rates()
    
    # Read sales.csv
    rows = []
    with open('sales.csv', 'r') as f:
        reader = csv.reader(f)
        header = next(reader)
        for row in reader:
            # Skip blank lines or malformed lines
            if len(row) < 7:
                continue
            
            # Skip repeated header
            if row[0] == 'Id':
                continue
            
            # Extract fields
            record_id = row[0].strip()
            date_str = row[1]
            item = row[2].strip()
            amount_str = row[3]
            currency = row[4]
            edited_str = row[5]
            notes = row[6] # Not used in output
            
            # Parse date
            dt = parse_date(date_str)
            if dt is None:
                continue
            
            # Parse amount
            usd_amount = parse_amount(amount_str, currency)
            if usd_amount is None:
                continue
            
            # Parse edited time
            # Format: YYYY-MM-DD HH:MM or YYYY-MM-DD H:MM
            # Normalize to parse
            edited_dt = None
            try:
                # Try standard format
                edited_dt = datetime.strptime(edited_str.strip(), '%Y-%m-%d %H:%M')
            except ValueError:
                try:
                    # Try with single digit hour
                    edited_dt = datetime.strptime(edited_str.strip(), '%Y-%m-%d %H:%M')
                except ValueError:
                    # Try replacing single digit hour
                    # e.g. "2026-01-06 9:05" -> "2026-01-06 09:05"
                    parts = edited_str.strip().split(' ')
                    if len(parts) == 2:
                        time_part = parts[1]
                        date_part = parts[0]
                        time_parts = time_part.split(':')
                        if len(time_parts) == 2:
                            hour = int(time_parts[0])
                            minute = int(time_parts[1])
                            formatted_time = f"{hour:02d}:{minute:02d}"
                            try:
                                edited_dt = datetime.strptime(f"{date_part} {formatted_time}", '%Y-%m-%d %H:%M')
                            except ValueError:
                                pass
        
            if edited_dt is None:
                continue
            
            rows.append({
                'id': record_id,
                'date': dt,
                'item': item,
                'amount': usd_amount,
                'edited': edited_dt
            })
    
    # Deduplicate by Id: keep the one with latest Edited time
    # If same Edited time, keep one
    best_rows = {}
    for row in rows:
        rid = row['id']
        if rid not in best_rows:
            best_rows[rid] = row
        else:
            if row['edited'] > best_rows[rid]['edited']:
                best_rows[rid] = row
    
    # Sort by date, then by item
    sorted_rows = sorted(best_rows.values(), key=lambda r: (r['date'], r['item']))
    
    # Write cleaned.csv
    with open('cleaned.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['date', 'item', 'amount'])
        for row in sorted_rows:
            date_str = row['date'].strftime('%Y-%m-%d')
            item = row['item']
            amount = row['amount']
            # Format amount with 2 decimals
            amount_str = f"{amount:.2f}"
            writer.writerow([date_str, item, amount_str])
    
    # Write totals.json
    monthly_totals = defaultdict(float)
    for row in sorted_rows:
        month_key = row['date'].strftime('%Y-%m')
        monthly_totals[month_key] += row['amount']
    
    # Round totals to 2 decimals
    totals_json = {}
    for month in sorted(monthly_totals.keys()):
        totals_json[month] = round(monthly_totals[month], 2)
    
    with open('totals.json', 'w') as f:
        json.dump(totals_json, f)
    
    # Write items.json
    item_totals = defaultdict(float)
    for row in sorted_rows:
        item_totals[row['item']] += row['amount']
    
    items_list = []
    for item, total in item_totals.items():
        items_list.append({'item': item, 'total': round(total, 2)})
    
    # Sort by total descending, then by name ascending
    items_list.sort(key=lambda x: (-x['total'], x['item']))
    
    with open('items.json', 'w') as f:
        json.dump(items_list, f)
    
    # Write medians.json
    monthly_amounts = defaultdict(list)
    for row in sorted_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:
            # Even number: halfway between two middle amounts
            mid1 = amounts[n // 2 - 1]
            mid2 = amounts[n // 2]
            median = (mid1 + mid2) / 2
        
        # Round to 2 decimals, if half cent, round up
        # Python's round uses banker's rounding, so we need to handle this manually
        # "if that lands on half a cent, round it up (12.345 becomes 12.35)"
        # 12.345 -> 12.35 (round half up)
        
        # To implement round half up:
        # Multiply by 100, add 0.5, floor, divide by 100
        median_rounded = math.floor(median * 100 + 0.5) / 100
        
        medians_json[month] = round(median_rounded, 2)
    
    with open('medians.json', 'w') as f:
        json.dump(medians_json, f)
    
    # Write chart.svg
    # Bar chart of monthly totals
    months = sorted(totals_json.keys())
    if not months:
        # Empty chart
        dwg = svgwrite.Drawing('chart.svg', size=(800, 600))
        dwg.write()
        return
    
    max_total = max(totals_json.values())
    min_total = min(totals_json.values())
    
    # Chart dimensions
    width = 800
    height = 600
    margin_left = 80
    margin_right = 50
    margin_top = 80
    margin_bottom = 100
    
    chart_width = width - margin_left - margin_right
    chart_height = height - margin_top - margin_bottom
    
    # Determine bar width and spacing
    num_bars = len(months)
    spacing = 20
    bar_width = (chart_width - spacing * (num_bars + 1)) / num_bars
    
    dwg = svgwrite.Drawing('chart.svg', size=(width, height))
    
    # Add title
    title = svgwrite.text.Text('Monthly Sales Totals', insert=(width / 2, 40), fill='black', font_size=20, text_anchor='middle')
    dwg.add(title)
    
    # Draw axes
    # X axis
    dwg.add(dwg.line((margin_left, margin_top + chart_height), (width - margin_right, margin_top + chart_height), stroke='black'))
    # Y axis
    dwg.add(dwg.line((margin_left, margin_top), (margin_left, margin_top + chart_height), stroke='black'))
    
    # Draw bars
    for i, month in enumerate(months):
        total = totals_json[month]
        bar_height = (total / max_total) * chart_height if max_total > 0 else 0
        
        x = margin_left + spacing + i * (bar_width + spacing)
        y = margin_top + chart_height - bar_height
        
        rect = svgwrite.shapes.Rect((x, y), width=bar_width, height=bar_height, fill='blue', class_='bar')
        dwg.add(rect)
        
        # Label
        label = svgwrite.text.Text(month, insert=(x + bar_width / 2, margin_top + chart_height + 20), fill='black', font_size=12, text_anchor='middle')
        dwg.add(label)
    
    dwg.write()

if __name__ == '__main__':
    main()
