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

export async function applySheetsActions(ctx: HandlerContext): Promise<void> {
    const { aiMessage, report } = ctx;
    let match: RegExpExecArray | null;

    // Action 10/11/12: Google Sheets read / write / append.
    // 모두 spreadsheet_id (속성) + range (속성) 필수. write/append 는 본문이 TSV.
    //   <read_sheet spreadsheet_id="1abc..." range="Sheet1!A1:D20"/>
    //   <write_sheet spreadsheet_id="1abc..." range="Sheet1!A1">
    //     이름\t나이\t직책
    //     민지\t29\t디자이너
    //   </write_sheet>
    //   <append_sheet spreadsheet_id="1abc..." range="Sheet1!A:C">
    //     2026-05-21\t새 항목\t완료
    //   </append_sheet>
    const sheetReadRegex = /<read_sheet\b([^>/]*?)\s*\/>/gi;
    while ((match = sheetReadRegex.exec(aiMessage)) !== null) {
        const a = _parseSheetAttrs(match[1]);
        if (!a.spreadsheetId || !a.range) {
            report.push(`❌ Sheet Read: spreadsheet_id / range 누락`);
            continue;
        }
        try {
            const { readSheetRange, valuesToMarkdownTable } = await import('../../features/sheets');
            const r = await readSheetRange(ctx.context, a.spreadsheetId, a.range);
            if (r.ok) {
                const md = valuesToMarkdownTable(r.values);
                report.push(`📊 Sheet Read: ${a.spreadsheetId.slice(0, 8)}…/${r.range} (${r.values.length} rows)`);
                ctx.chatHistory.push({
                    role: 'system',
                    content: `[Sheet read ${r.range}]\n${md}`,
                    internal: true,
                });
            } else {
                report.push(`❌ Sheet Read Failed: ${r.error}`);
            }
        } catch (err: any) { report.push(`❌ Sheet Read Error: ${err?.message ?? String(err)}`); }
    }
    const sheetWriteRegex = /<write_sheet\b([^>]*)>([\s\S]*?)<\/write_sheet>/gi;
    while ((match = sheetWriteRegex.exec(aiMessage)) !== null) {
        const a = _parseSheetAttrs(match[1]);
        const body = match[2];
        if (!a.spreadsheetId || !a.range) {
            report.push(`❌ Sheet Write: spreadsheet_id / range 누락`);
            continue;
        }
        try {
            const { writeSheetRange, parseTsvBody } = await import('../../features/sheets');
            const values = parseTsvBody(body);
            if (values.length === 0) {
                report.push(`❌ Sheet Write: 본문 비어있음`);
                continue;
            }
            const r = await writeSheetRange(ctx.context, a.spreadsheetId, a.range, values);
            if (r.ok) {
                report.push(`📊 Sheet Write: ${r.updatedRange} (${r.updatedCells} cells)`);
            } else {
                report.push(`❌ Sheet Write Failed: ${r.error}`);
            }
        } catch (err: any) { report.push(`❌ Sheet Write Error: ${err?.message ?? String(err)}`); }
    }
    const sheetAppendRegex = /<append_sheet\b([^>]*)>([\s\S]*?)<\/append_sheet>/gi;
    while ((match = sheetAppendRegex.exec(aiMessage)) !== null) {
        const a = _parseSheetAttrs(match[1]);
        const body = match[2];
        if (!a.spreadsheetId || !a.range) {
            report.push(`❌ Sheet Append: spreadsheet_id / range 누락`);
            continue;
        }
        try {
            const { appendSheetRows, parseTsvBody } = await import('../../features/sheets');
            const values = parseTsvBody(body);
            if (values.length === 0) {
                report.push(`❌ Sheet Append: 본문 비어있음`);
                continue;
            }
            const r = await appendSheetRows(ctx.context, a.spreadsheetId, a.range, values);
            if (r.ok) {
                report.push(`📊 Sheet Append: ${r.appendedRange} (${r.updatedCells} cells)`);
            } else {
                report.push(`❌ Sheet Append Failed: ${r.error}`);
            }
        } catch (err: any) { report.push(`❌ Sheet Append Error: ${err?.message ?? String(err)}`); }
    }
}
