import sqlite3
import json
import random
from datetime import datetime, timedelta

DB_NAME = "health_data.db"

def create_dummy_graph(base_bpm, duration_sec=150):
    """
    Generates a realistic looking heart rate graph.
    It takes a base BPM and adds slight fluctuations 
    so it looks like a real human heart rate trend.
    """
    graph = []
    current_bpm = base_bpm
    
    for _ in range(duration_sec):
        # Simulate small natural fluctuation (+1, -1, or 0)
        change = random.choice([-1, 0, 1])
        
        # Occasional larger jump (breath in/out)
        if random.random() < 0.1: 
            change = random.choice([-2, 2])
            
        current_bpm += change
        
        # Keep it within realistic bounds relative to base
        if current_bpm > base_bpm + 10: current_bpm -= 1
        if current_bpm < base_bpm - 10: current_bpm += 1
        
        graph.append(current_bpm)
        
    return graph

def seed_database():
    print(f"Connecting to {DB_NAME}...")
    
    # Connect to DB
    conn = sqlite3.connect(DB_NAME)
    cursor = conn.cursor()

    # Create table if it doesn't exist (just in case)
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS measurements (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp DATETIME,
            avg_bpm INTEGER,
            avg_spo2 REAL,
            avg_temp_f REAL,
            bpm_graph TEXT,
            valid INTEGER,
            reason TEXT
        )
    ''')

    # --- GENERATE DATA ---
    records = []
    
    # Generate 15 records
    for i in range(15):
        # Time: going back in time (latest first)
        record_time = datetime.now() - timedelta(hours=i*2, minutes=random.randint(0, 59))
        timestamp_str = record_time.strftime("%Y-%m-%d %H:%M:%S")

        # 80% chance of being Valid, 20% Invalid
        is_valid = 1 if random.random() > 0.2 else 0

        if is_valid:
            # Healthy ranges
            avg_spo2 = round(random.uniform(96.0, 99.9), 1)
            avg_temp_f = round(random.uniform(97.5, 99.2), 1)
            base_bpm = random.randint(60, 90)
            
            # Create graph data
            bpm_graph = create_dummy_graph(base_bpm)
            
            # Calculate exact average from graph
            real_avg_bpm = int(sum(bpm_graph) / len(bpm_graph))
            
            reason = ""
            
            records.append((timestamp_str, real_avg_bpm, avg_spo2, avg_temp_f, json.dumps(bpm_graph), 1, reason))
        
        else:
            # Invalid data (simulating finger removed too soon)
            avg_spo2 = 0
            avg_temp_f = 0
            avg_bpm = 0
            bpm_graph = json.dumps([]) # Empty graph
            reason = "Insufficient Duration"
            
            records.append((timestamp_str, avg_bpm, avg_spo2, avg_temp_f, bpm_graph, 0, reason))

    # --- INSERT DATA ---
    print(f"Inserting {len(records)} dummy records...")
    cursor.executemany('''
        INSERT INTO measurements (timestamp, avg_bpm, avg_spo2, avg_temp_f, bpm_graph, valid, reason)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ''', records)

    conn.commit()
    conn.close()
    print("Success! Database populated.")

if __name__ == "__main__":
    seed_database()