use crate::db::queries::{ProjectQueries, SessionQueries};
use crate::models::{Project, Session, SessionContext};
use anyhow::Result;
use chrono::{Duration, Utc};
use rand::Rng;
use rusqlite::Connection;
use std::path::PathBuf;

pub fn seed_database(conn: &Connection) -> Result<()> {
    println!("Seeding database...");

    // 1. Clear existing data
    conn.execute("DELETE FROM sessions", [])?;
    conn.execute("DELETE FROM projects", [])?;
    conn.execute("DELETE FROM tags", [])?;
    conn.execute("DELETE FROM goals", [])?;

    // Reset auto-increment counters
    conn.execute("DELETE FROM sqlite_sequence WHERE name='sessions'", [])?;
    conn.execute("DELETE FROM sqlite_sequence WHERE name='projects'", [])?;
    conn.execute("DELETE FROM sqlite_sequence WHERE name='tags'", [])?;
    conn.execute("DELETE FROM sqlite_sequence WHERE name='goals'", [])?;

    println!("Database cleared.");

    // 2. Create dummy projects
    let projects = vec![
        (
            "LLM Fine-tuning",
            "Fine-tuning Llama 3 on custom dataset",
            "/Users/darylwanji/projects/llm-finetune",
        ),
        (
            "RAG Pipeline",
            "Retrieval Augmented Generation for internal docs",
            "/Users/darylwanji/projects/rag-pipeline",
        ),
        (
            "Computer Vision Model",
            "Object detection for autonomous drone",
            "/Users/darylwanji/projects/cv-drone",
        ),
        (
            "Reinforcement Learning Agent",
            "PPO agent for trading bot",
            "/Users/darylwanji/projects/rl-trading",
        ),
        (
            "Data Pipeline ETL",
            "ETL pipeline for customer data",
            "/Users/darylwanji/projects/etl-pipeline",
        ),
    ];

    let mut project_ids = Vec::new();

    for (name, desc, path) in projects {
        let project = Project {
            id: None,
            name: name.to_string(),
            path: PathBuf::from(path),
            git_hash: Some("a1b2c3d".to_string()), // Dummy hash
            description: Some(desc.to_string()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            is_archived: false,
        };

        let id = ProjectQueries::create(conn, &project)?;
        project_ids.push(id);
        println!("Created project: {}", name);
    }

    // 3. Create dummy sessions
    let mut rng = rand::thread_rng();
    let contexts = vec![
        SessionContext::Terminal,
        SessionContext::IDE,
        SessionContext::Linked,
        SessionContext::Manual,
    ];
    let notes = vec![
        "Debugging model convergence",
        "Implementing attention mechanism",
        "Optimizing data loader",
        "Refactoring training loop",
        "Writing documentation",
        "Code review",
        "Meeting with team",
        "Testing inference speed",
    ];

    for &project_id in &project_ids {
        // Create 10-20 sessions per project
        let num_sessions = rng.gen_range(10..21);

        for _ in 0..num_sessions {
            // Random start time in the last 30 days
            let days_ago = rng.gen_range(0..30);
            let hours_ago = rng.gen_range(0..24);
            let start_time = Utc::now() - Duration::days(days_ago) - Duration::hours(hours_ago);

            // Random duration between 15 mins and 4 hours
            let duration_mins = rng.gen_range(15..240);
            let end_time = start_time + Duration::minutes(duration_mins);

            let context = contexts[rng.gen_range(0..contexts.len())];
            let note = if rng.gen_bool(0.3) {
                Some(notes[rng.gen_range(0..notes.len())].to_string())
            } else {
                None
            };

            let session = Session {
                id: None,
                project_id,
                start_time,
                end_time: Some(end_time),
                context,
                paused_duration: Duration::zero(),
                notes: note,
                created_at: start_time,
            };

            SessionQueries::create(conn, &session)?;
        }
        println!(
            "Created {} sessions for project {}",
            num_sessions, project_id
        );
    }

    println!("Database seeding completed successfully.");
    Ok(())
}
