import { storage } from '../server/storage';
import { db } from '../server/db';
import { users, tasks, labels } from '../shared/schema';
import { scrypt, randomBytes } from "crypto";
import { promisify } from "util";

const scryptAsync = promisify(scrypt);

async function hashPassword(password: string) {
    const salt = randomBytes(16).toString("hex");
    const buf = (await scryptAsync(password, salt, 64)) as Buffer;
    return `${buf.toString("hex")}.${salt}`;
}

async function seedAiTest() {
    console.log("🌱 Seeding AI Benchmark Tasks...");

    // 1. Get User
    let user = await storage.getUserByUsername('admin');
    if (!user) user = await storage.getUserByUsername('paul');
    if (!user) {
        console.error("❌ No user found.");
        process.exit(1);
    }

    // Reset Password
    const newPass = await hashPassword('admin123');
    await storage.updateUser(user.id, { password: newPass });
    console.log(`🔑 Reset Password for ${user.username} to 'admin123'`);

    // Check AI Settings
    // Check AI Settings
    const provider = await storage.getSystemSettings("ai_provider");
    const key = await storage.getSystemSettings("ai_api_key");
    const model = await storage.getSystemSettings("ai_model");
    console.log(`🤖 AI Configuration: Provider=${provider || 'default(openai)'}, Model=${model || 'default'}, KeySet=${!!key}`);

    // 3. Create Labels
    let workLabel = await storage.createLabel({ name: 'Work', color: '#3b82f6', creatorId: user.id });
    let personalLabel = await storage.createLabel({ name: 'Personal', color: '#10b981', creatorId: user.id });

    // Handle potential duplication if labels already exist (storage.createLabel might return existing?)
    // server/storage.ts doesn't dedupe by name usually?
    // server/ai.ts createLabel tool logic specifically checks for existing.
    // Let's assume for this script we just create them or continue.

    // 4. Create Tasks
    const tasksToCreate = [
        {
            title: "Review quarterly report",
            status: "todo",
            priority: "high",
            labelId: workLabel.id,
            userId: user.id
        },
        {
            title: "Buy milk",
            status: "todo",
            priority: "medium",
            labelId: personalLabel.id,
            userId: user.id
        },
        {
            title: "Review movie script",
            status: "todo",
            priority: "low",
            labelId: personalLabel.id,
            userId: user.id
        }
    ];

    for (const t of tasksToCreate) {
        await storage.createTask(t);
        console.log(`Created task: "${t.title}" [${t.labelId === workLabel.id ? 'Work' : 'Personal'}]`);
    }

    console.log("✅ Seeding Complete. ready for AI usage.");
    process.exit(0);
}

seedAiTest();
