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

export async function applyCalendarActions(ctx: HandlerContext): Promise<void> {
    const { aiMessage, report } = ctx;
    let match: RegExpExecArray | null;
    // Action 8: Create Calendar Event (OAuth) — agent 가 회의록·작업 분석 후 일정 자동 생성.
    // 형식: <create_calendar_event title="..." start="2026-05-21T14:00" duration="60" location="...">설명</create_calendar_event>
    // 속성: title (필수), start (필수, ISO 'YYYY-MM-DDTHH:MM' 또는 timezone 포함),
    //       end | duration (분, default 60), location, all_day (true/false)
    const calRegex = /<create_calendar_event\b([^>]*)>([\s\S]*?)<\/create_calendar_event>/gi;
    while ((match = calRegex.exec(aiMessage)) !== null) {
        const attrs = _parseCalEventAttrs(match[1]);
        const desc = match[2].trim();
        if (!attrs.title || !attrs.start) {
            report.push(`❌ Calendar Event: title / start 누락`);
            continue;
        }
        try {
            const { createCalendarEvent } = await import('../../features/calendar');
            const r = await createCalendarEvent(ctx.context, {
                title: attrs.title,
                start: attrs.start,
                end: attrs.end,
                durationMinutes: attrs.duration,
                location: attrs.location,
                description: desc || undefined,
                allDay: attrs.allDay,
            });
            if (r.ok) {
                report.push(`📅 Calendar Event Created: ${r.event.title} (${r.event.startIso})`);
                // chatHistory 에 결과 주입 — agent 가 다음 답변에서 link 인용 가능.
                ctx.chatHistory.push({
                    role: 'system',
                    content: `[Calendar event created] ${r.event.title} · ${r.event.startIso}\nLink: ${r.event.htmlLink}`,
                    internal: true,
                });
            } else {
                report.push(`❌ Calendar Event Failed: ${r.error}`);
            }
        } catch (err: any) { report.push(`❌ Calendar Event Error: ${err?.message ?? String(err)}`); }
    }
}
