export const extractPartialTodos = (jsonText) => {
    try {
        const parsed = JSON.parse(jsonText);
        const result = Array.isArray(parsed) ? parsed : parsed?.items || [];
        return result;
    }
    catch (e) {
        const items = [];
        const textPattern = /"text"\s*:\s*"([^"]+)"/g;
        const textMatches = [];
        let textMatch;
        while ((textMatch = textPattern.exec(jsonText)) !== null) {
            if (textMatch[1]) {
                textMatches.push({
                    text: textMatch[1],
                    startIdx: textMatch.index,
                });
            }
        }
        for (const { startIdx } of textMatches) {
            let openBrace = -1;
            for (let i = startIdx - 1; i >= 0; i--) {
                if (jsonText[i] === "{") {
                    openBrace = i;
                    break;
                }
                if (jsonText[i] === "}")
                    break;
            }
            if (openBrace === -1)
                continue;
            let closeBrace = -1;
            let depth = 0;
            for (let i = openBrace; i < jsonText.length; i++) {
                if (jsonText[i] === "{")
                    depth++;
                if (jsonText[i] === "}") {
                    depth--;
                    if (depth === 0) {
                        closeBrace = i;
                        break;
                    }
                }
            }
            const objStr = closeBrace !== -1
                ? jsonText.substring(openBrace, closeBrace + 1)
                : jsonText.substring(openBrace) + "}";
            try {
                const obj = JSON.parse(objStr);
                if (obj.title || obj.text) {
                    items.push({
                        title: obj.title || obj.text,
                        status: obj.status || "pending",
                        instructions: obj.instructions || obj.note || undefined,
                        agentProfileId: obj.agentProfileId || undefined,
                    });
                }
            }
            catch (e) {
                // Skip malformed objects
            }
        }
        const lines = jsonText.split("\n");
        for (let i = lines.length - 1; i >= 0; i--) {
            const partialJson = lines.slice(0, i + 1).join("\n");
            let testJson = partialJson;
            const openBraces = (testJson.match(/\{/g) || []).length;
            const closeBraces = (testJson.match(/\}/g) || []).length;
            const openBrackets = (testJson.match(/\[/g) || []).length;
            const closeBrackets = (testJson.match(/\]/g) || []).length;
            testJson += "]".repeat(openBrackets - closeBrackets);
            testJson += "}".repeat(openBraces - closeBraces);
            try {
                const parsed = JSON.parse(testJson);
                const partialItems = Array.isArray(parsed)
                    ? parsed
                    : parsed?.items || [];
                if (partialItems.length > items.length) {
                    return partialItems;
                }
            }
            catch (e) {
                continue;
            }
        }
        return items;
    }
};
export const extractTodosFromMessages = (messages) => {
    const todos = [];
    const fencedTodoToken = "```todo_list";
    const plainTodoToken = "todo_list";
    for (const message of messages) {
        if (message.role !== "assistant" || !message.content)
            continue;
        const content = message.content;
        let cursor = 0;
        while (cursor < content.length) {
            const nextFenced = content.indexOf(fencedTodoToken, cursor);
            const nextPlain = content.indexOf(plainTodoToken, cursor);
            let todoStart = -1;
            let isFenced = false;
            if (nextFenced !== -1 && (nextPlain === -1 || nextFenced < nextPlain)) {
                todoStart = nextFenced;
                isFenced = true;
            }
            else if (nextPlain !== -1) {
                const before = nextPlain > 0 ? content[nextPlain - 1] : "\n";
                if (before === "\n" || before === "\r" || nextPlain === 0) {
                    todoStart = nextPlain;
                    isFenced = false;
                }
            }
            if (todoStart === -1)
                break;
            try {
                let jsonText = "";
                let isComplete = true;
                if (isFenced) {
                    const afterToken = todoStart + fencedTodoToken.length;
                    const closePos = content.indexOf("```", afterToken);
                    if (closePos === -1) {
                        jsonText = content.slice(afterToken).trim();
                        isComplete = false;
                        cursor = content.length;
                    }
                    else {
                        jsonText = content.slice(afterToken, closePos).trim();
                        cursor = closePos + 3;
                    }
                }
                else {
                    const afterToken = todoStart + plainTodoToken.length;
                    const braceStart = content.indexOf("{", afterToken);
                    if (braceStart === -1)
                        break;
                    let depth = 0;
                    let braceEnd = -1;
                    for (let i = braceStart; i < content.length; i++) {
                        if (content[i] === "{")
                            depth++;
                        if (content[i] === "}") {
                            depth--;
                            if (depth === 0) {
                                braceEnd = i;
                                break;
                            }
                        }
                    }
                    if (braceEnd === -1) {
                        jsonText = content.slice(braceStart).trim();
                        isComplete = false;
                        cursor = content.length;
                    }
                    else {
                        jsonText = content.slice(braceStart, braceEnd + 1).trim();
                        cursor = braceEnd + 1;
                    }
                }
                const todoItems = isComplete
                    ? (() => {
                        try {
                            const parsed = JSON.parse(jsonText);
                            return Array.isArray(parsed) ? parsed : parsed?.items || [];
                        }
                        catch (e) {
                            return [];
                        }
                    })()
                    : extractPartialTodos(jsonText);
                todoItems.forEach((item) => {
                    if (!item)
                        return;
                    const title = item.title ||
                        item.text ||
                        item.content ||
                        item.label ||
                        String(item.task || "");
                    if (!title)
                        return;
                    todos.push({
                        id: item.id,
                        title,
                        status: item.status || "pending",
                        instructions: item.instructions || item.note || item.description,
                        agentProfileId: item.agentProfileId,
                        messageId: message.id,
                        sourceTitle: item.sourceTitle,
                    });
                });
            }
            catch (e) {
                cursor++;
                continue;
            }
        }
    }
    const todoMap = new Map();
    for (const todo of todos) {
        const key = todo.id || todo.title;
        todoMap.set(key, todo);
    }
    return Array.from(todoMap.values());
};
//# sourceMappingURL=agentTodoExtraction.js.map