
import { AiService } from "./ai";
import { MemStorage } from "./storage";
import { User } from "../shared/schema";

async function run() {
    console.log("Starting Subtask Repro...");
    const storage = new MemStorage();

    // Create dummy user
    const user: User = await storage.createUser({
        username: "testuser",
        password: "hashedpassword",
        role: "user",
        aiEnabled: true,
        xp: 0,
        level: 1
    });

    // Mock settings - Use env variables if available for real testing, or mock if just testing logic flow (but we need real AI for logic flow testing)
    if (process.env.OPENAI_API_KEY) {
        await storage.updateSystemSetting("ai_provider", "openai");
        await storage.updateSystemSetting("ai_api_key", process.env.OPENAI_API_KEY);
        await storage.updateSystemSetting("ai_model", "gpt-4o");
    } else {
        console.warn("No OPENAI_API_KEY provided. This test requires a valid key to actually hit the AI.");
        process.exit(1);
    }

    const aiService = new AiService(storage);

    // Scenario 1: Create new parent and subtask in one go
    console.log("\n--- Scenario 1: Create New Parent + Subtask ---");
    const prompt1 = "Create a task 'Main Project A'. Then create a subtask 'Subtask A1' for it. Also edit 'Subtask A1' to be 'In Progress'.";
    try {
        const response1 = await aiService.chat(
            [{ role: "user", content: prompt1 }],
            user,
            "Current Date: 2025-12-12. No existing tasks."
        );
        console.log("Response 1:", response1);
    } catch (e) {
        console.error("Error in Scenario 1:", e);
    }

    const tasks1 = await storage.getTasks(user.id);
    console.log("Tasks after Scenario 1:", tasks1);

    // Scenario 2: Add subtask to existing task
    console.log("\n--- Scenario 2: Add Subtask to Existing ---");
    // Create an existing task manually first
    const existingTask = await storage.createTask({
        title: "Existing Project B",
        priority: "high",
        status: "todo",
        userId: user.id
    });
    console.log("Created existing task:", existingTask.id, existingTask.title);

    const prompt2 = "Add a subtask 'Subtask B1' to 'Existing Project B'.";
    try {
        const response2 = await aiService.chat(
            [{ role: "user", content: prompt2 }],
            user,
            `Current Date: 2025-12-12.`
        );
        console.log("Response 2:", response2);
    } catch (e) {
        console.error("Error in Scenario 2:", e);
    }

    const tasks2 = await storage.getTasks(user.id);
    console.log("Final Task List:", tasks2.map(t => ({ id: t.id, title: t.title, parent: t.parentTaskId, status: t.status })));
}

run();
