import csv
from datetime import datetime

def convert_weight_data():
    weight_data = []
    with open('Weight.csv', 'r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        for row in reader:
            date_time = datetime.strptime(row['start_time'], '%Y-%m-%d %H:%M')
            weight_data.append([
                'Weight',
                date_time.strftime('%Y-%m-%d'),
                date_time.strftime('%H:%M:%S'),
                row['weight'],
                '',
                'kg',
                '',
                row['comment']
            ])
    return weight_data

def convert_bp_data():
    bp_data = []
    with open('Blood Pressure.csv', 'r', encoding='utf-8-sig') as f:
        reader = csv.DictReader(f)
        for row in reader:
            date_time = datetime.strptime(row['start_time'], '%Y-%m-%d %H:%M')
            bp_data.append([
                'Blood Pressure',
                date_time.strftime('%Y-%m-%d'),
                date_time.strftime('%H:%M:%S'),
                row['systolic'],
                row['diastolic'],
                'mmHg',
                '',
                row['comment']
            ])
    return bp_data

# Convert data
weight_entries = convert_weight_data()
bp_entries = convert_bp_data()

# Combine and sort by date/time
all_entries = weight_entries + bp_entries
all_entries.sort(key=lambda x: datetime.strptime(f"{x[1]} {x[2]}", '%Y-%m-%d %H:%M:%S'))

# Write to new CSV
with open('historical_data_import.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Type', 'Date', 'Time', 'Value1', 'Value2', 'Unit', 'Category', 'Notes'])
    writer.writerows(all_entries)

print(f"Converted {len(weight_entries)} weight entries and {len(bp_entries)} blood pressure entries")
print("Output saved to: historical_data_import.csv")
