// BEGIN_SAMPLE_ONLY — 가상 샘플입니다. 실제 메일이 아닙니다.
const SAMPLES = [
  {id: 'DEMO-001', subject: '예약 날짜 문의', body: '2026-11-07 오후 2시 4명 예약 가능한가요?', from: 'demo1@example.invalid'},
  {id: 'DEMO-002', subject: '가격 및 취소 문의', body: '4명 이용 가격과 취소 규정 알려주세요.', from: 'demo2@example.invalid'}
];
function safeText_(value) {
  const text = String(value == null ? '' : value).replace(/\u0000/g, '').slice(0, 20000);
  return /^[\s\uFEFF\u200B-\u200D]*[=+@-]/.test(text) ? '[TEXT] ' + text : text;
}
function mailbox_(value) {
  const text = String(value || '').trim();
  if (/[\r\n,;]/.test(text)) throw new Error('ADDRESS_REVIEW');
  const match = text.match(/^[^<>]*<([^<>]+)>$/);
  const address = match ? match[1].trim() : text;
  if (!/^[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9-]+(?:\.[A-Z0-9-]+)+$/i.test(address)) {
    throw new Error('ADDRESS_REVIEW');
  }
  return address;
}
function plan_(mail) {
  const from = mailbox_(mail.from), to = mailbox_(mail.replyTo || mail.from);
  if (from.toLowerCase() !== to.toLowerCase()) throw new Error('REPLY_TO_REVIEW');
  const text = String(mail.subject || '') + '\n' + String(mail.body || '').slice(0, 10000);
  const category = /예약|reservation|booking/i.test(text) ? '예약' :
    /가격|요금|금액|취소|환불|price|cost|cancel|refund/i.test(text) ? '가격' : '기타';
  const phrases = {
    '예약': '요청하신 날짜와 인원의 예약 가능 여부를 확인 중입니다. 아직 예약이 확정되지 않았습니다.',
    '가격': '이용 가격과 취소·환불 규정을 확인 중입니다. 확인된 금액이나 조건은 아직 안내드릴 수 없습니다.',
    '기타': '문의하신 내용을 확인 중입니다.'
  };
  const draft = '안녕하세요. 문의해 주셔서 감사합니다.\n\n' + phrases[category] +
    '\n가격·예약 확정·취소 및 환불 조건은 담당자 확인이 필요합니다.\n\n감사합니다.';
  return {category, to, draft};
}
function sampleBatch_(items, previousIds) {
  const ids = new Set(previousIds), rows = [];
  for (const mail of items) {
    if (ids.has(mail.id)) continue;
    const plan = plan_(mail);
    rows.push({id: mail.id, category: plan.category, to: plan.to, draft: plan.draft, status: 'DONE', simulated: true});
    ids.add(mail.id);
  }
  return {ids: Array.from(ids), rows};
}
function runSample() {
  const result = sampleBatch_(SAMPLES, []);
  const report = {title: '가상 샘플 — 실제 메일 아님', processed: result.rows.length, results: result.rows};
  console.log(JSON.stringify(report, null, 2));
  return report;
}
function runSampleTwice() {
  const first = sampleBatch_(SAMPLES, []), second = sampleBatch_(SAMPLES, first.ids);
  const passed = first.rows.length === 2 && second.rows.length === 0;
  if (!passed) throw new Error('SAMPLE_DUPLICATE_CHECK_FAILED');
  const report = {title: '가상 중복 검증 — 실제 메일 아님', first: first.rows.length, second: second.rows.length, passed};
  console.log(JSON.stringify(report, null, 2));
  return report;
}
// END_SAMPLE_ONLY — 위 구간만 복사하면 서비스 코드가 없는 샘플이 됩니다.

const CONFIG = Object.freeze({enabled: false, label: 'AI핫플-문의실습'});
const HEADERS = ['messageId', 'receivedAtUTC', 'from', 'replyTo', 'subject', 'category', 'draftText', 'status', 'draftId', 'note'];
function writeRow_(sheet, number, values) {
  sheet.getRange(number, 1, 1, HEADERS.length).setNumberFormat('@').setValues([values.map(safeText_)]);
  SpreadsheetApp.flush(); // 상태 기록이 완료된 뒤에만 초안을 생성합니다.
}
function setupSheet() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) { console.log('BUSY'); return; }
  try {
    const props = PropertiesService.getScriptProperties();
    if (props.getProperty('INQUIRY_SHEET_ID')) { console.log('SETUP_EXISTS'); return; }
    const book = SpreadsheetApp.create('AI핫플 문의 실습 - 테스트 전용');
    const sheet = book.getSheets()[0].setName('문의');
    writeRow_(sheet, 1, HEADERS);
    sheet.setFrozenRows(1);
    props.setProperty('INQUIRY_SHEET_ID', book.getId());
    console.log('SETUP_OK');
  } catch (_) { console.log('SETUP_FAILED_MANUAL_CHECK'); }
  finally { lock.releaseLock(); }
}
function eligible_(meta, labelId, start, end) {
  const labels = meta.labelIds || [], time = Number(meta.internalDate);
  return Number.isFinite(time) && time >= start && time <= end && labels.includes(labelId) &&
    !['SENT', 'DRAFT', 'SPAM', 'TRASH'].some(label => labels.includes(label));
}
function processOne_(sheet, id, receivedAt) {
  const number = sheet.getLastRow() + 1;
  const row = [id, new Date(receivedAt).toISOString(), '', '', '', '', '', 'PROCESSING', '', ''];
  try {
    writeRow_(sheet, number, row);
    const message = GmailApp.getMessageById(id);
    row[2] = message.getFrom();
    row[3] = message.getReplyTo() || row[2];
    row[4] = message.getSubject();
    const plan = plan_({from: row[2], replyTo: row[3], subject: row[4], body: message.getPlainBody()});
    row[5] = plan.category;
    row[6] = plan.draft;
    writeRow_(sheet, number, row);
    const draft = message.createDraftReply(plan.draft);
    row[8] = draft.getId();
    row[7] = 'DONE';
    writeRow_(sheet, number, row);
    return 'done';
  } catch (error) {
    row[7] = 'ERROR';
    row[9] = ['ADDRESS_REVIEW', 'REPLY_TO_REVIEW'].includes(error.message) ? error.message : 'MANUAL_REVIEW';
    try { writeRow_(sheet, number, row); }
    catch (_) { throw new Error('ROW_STATE_UNKNOWN'); }
    return 'error';
  }
}
function processInquiries() {
  if (CONFIG.enabled !== true) { console.log('DISABLED'); return; }
  if (CONFIG.label !== 'AI핫플-문의실습') { console.log('LABEL_GUARD'); return; }
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) { console.log('BUSY'); return; }
  const counts = {scanned: 0, done: 0, error: 0, skipped: 0, status: 'OK'};
  try {
    const props = PropertiesService.getScriptProperties();
    const sheetId = props.getProperty('INQUIRY_SHEET_ID');
    if (!sheetId) throw new Error('SETUP_REQUIRED');
    const sheet = SpreadsheetApp.openById(sheetId).getSheetByName('문의');
    if (!sheet || sheet.getRange(1, 1, 1, HEADERS.length).getDisplayValues()[0].join('|') !== HEADERS.join('|')) {
      throw new Error('SHEET_SCHEMA_REVIEW');
    }
    const seen = new Set(sheet.getRange(1, 1, sheet.getLastRow(), 1).getDisplayValues().slice(1).map(row => row[0]));
    const label = (Gmail.Users.Labels.list('me').labels || []).find(item => item.name === CONFIG.label);
    if (!label) { counts.status = 'LABEL_MISSING'; return; }
    const end = Date.now(), start = end - 7 * 24 * 60 * 60 * 1000;
    let token;
    do {
      const options = {labelIds: [label.id], q: 'newer_than:7d -in:sent -in:drafts', maxResults: Math.min(20, 100 - counts.scanned), includeSpamTrash: false};
      if (token) options.pageToken = token;
      const page = Gmail.Users.Messages.list('me', options);
      for (const item of (page.messages || [])) {
        if (counts.scanned >= 100) break;
        counts.scanned++;
        if (seen.has(item.id)) { counts.skipped++; continue; }
        const meta = Gmail.Users.Messages.get('me', item.id, {format: 'metadata', fields: 'id,labelIds,internalDate'});
        if (!eligible_(meta, label.id, start, end)) { counts.skipped++; continue; }
        seen.add(item.id); // 상태와 관계없이 기존 ID는 다음 실행에서도 건너뜁니다.
        counts[processOne_(sheet, item.id, Number(meta.internalDate))]++;
      }
      token = page.nextPageToken;
    } while (token && counts.scanned < 100);
    if (counts.scanned >= 100) counts.status = 'LIMIT_REACHED';
  } catch (_) { counts.status = 'STOPPED_MANUAL_REVIEW'; }
  finally {
    lock.releaseLock();
    console.log(JSON.stringify(counts)); // 건수와 고정 상태 코드만 기록합니다.
  }
}
