import { HandlerContext } from './types';
import { _parseTaskAttrs } from '../attrParsers';

// Action 13/14/15: Task tracker — _shared/tasks.md 에 누적.
// 회의록·계획·작업 진척 추적의 단일 출처. status: open/in_progress/blocked/done.
//   <add_task title="..." owner="@me" due="2026-05-24T18:00" notes="..."/>
//   <update_task id="t_001" status="in_progress" notes="진행중"/>
//   <complete_task id="t_001"/>
export async function applyTasksActions(ctx: HandlerContext): Promise<void> {
    const { aiMessage, report } = ctx;
    let match: RegExpExecArray | null;

    const addTaskRegex = /<add_task\b([^>/]*?)\s*\/>/gi;
    while ((match = addTaskRegex.exec(aiMessage)) !== null) {
        const a = _parseTaskAttrs(match[1]);
        if (!a.title) { report.push(`❌ Add Task: title 누락`); continue; }
        try {
            const { readTaskStore, writeTaskStore, addTask } = await import('../../features/tasks');
            const store = readTaskStore(ctx.context);
            const created = addTask(store, {
                title: a.title,
                owner: a.owner,
                due: a.due,
                notes: a.notes,
                status: a.status,
            });
            writeTaskStore(ctx.context, store);
            report.push(`📋 Task Added: ${created.id} · ${created.title}${created.due ? ' (due ' + created.due + ')' : ''}`);
        } catch (err: any) { report.push(`❌ Add Task Error: ${err?.message ?? String(err)}`); }
    }
    const updTaskRegex = /<update_task\b([^>/]*?)\s*\/>/gi;
    while ((match = updTaskRegex.exec(aiMessage)) !== null) {
        const a = _parseTaskAttrs(match[1]);
        if (!a.id) { report.push(`❌ Update Task: id 누락`); continue; }
        try {
            const { readTaskStore, writeTaskStore, updateTask } = await import('../../features/tasks');
            const store = readTaskStore(ctx.context);
            const patch: any = {};
            if (a.title) patch.title = a.title;
            if (a.owner) patch.owner = a.owner;
            if (a.due) patch.due = a.due;
            if (a.notes) patch.notes = a.notes;
            if (a.status) patch.status = a.status;
            const updated = updateTask(store, a.id, patch);
            if (!updated) {
                report.push(`❌ Update Task: ${a.id} 를 active 목록에서 못 찾음`);
            } else {
                writeTaskStore(ctx.context, store);
                report.push(`📋 Task Updated: ${updated.id} → ${updated.status}${updated.due ? ' (due ' + updated.due + ')' : ''}`);
            }
        } catch (err: any) { report.push(`❌ Update Task Error: ${err?.message ?? String(err)}`); }
    }
    const compTaskRegex = /<complete_task\b([^>/]*?)\s*\/>/gi;
    while ((match = compTaskRegex.exec(aiMessage)) !== null) {
        const a = _parseTaskAttrs(match[1]);
        if (!a.id) { report.push(`❌ Complete Task: id 누락`); continue; }
        try {
            const { readTaskStore, writeTaskStore, completeTask } = await import('../../features/tasks');
            const store = readTaskStore(ctx.context);
            const closed = completeTask(store, a.id);
            if (!closed) {
                report.push(`❌ Complete Task: ${a.id} 못 찾음 (이미 done 이거나 존재 X)`);
            } else {
                writeTaskStore(ctx.context, store);
                report.push(`✅ Task Done: ${closed.id} · ${closed.title}`);
            }
        } catch (err: any) { report.push(`❌ Complete Task Error: ${err?.message ?? String(err)}`); }
    }
}
