function normalizeText(text) {
  return String(text ?? '').replace(/\s+/g, '').trim();
}

function chineseHourToNumber(value) {
  const raw = String(value ?? '').trim();
  if (/^\d{1,2}$/.test(raw)) return Number(raw);
  const map = {
    零: 0,
    一: 1,
    二: 2,
    两: 2,
    三: 3,
    四: 4,
    五: 5,
    六: 6,
    七: 7,
    八: 8,
    九: 9,
    十: 10,
  };
  if (raw === '十') return 10;
  if (raw.startsWith('十')) return 10 + (map[raw.slice(1)] ?? 0);
  if (raw.endsWith('十')) return (map[raw[0]] ?? 0) * 10;
  if (raw.includes('十')) {
    const [tens, ones] = raw.split('十');
    return (map[tens] ?? 1) * 10 + (map[ones] ?? 0);
  }
  return map[raw] ?? null;
}

function parseHourMinute(text) {
  const match = text.match(/(?:早上|上午|清晨|每天早上|每天上午)?([0-9]{1,2}|[零一二两三四五六七八九十]{1,3})(?:点|:|：)(半|[0-9]{1,2}分?)?/);
  if (!match) return null;
  const hour = chineseHourToNumber(match[1]);
  if (hour === null || hour < 0 || hour > 23) return null;
  let minute = 0;
  if (match[2] === '半') minute = 30;
  else if (match[2]) minute = Number(String(match[2]).replace('分', ''));
  if (!Number.isFinite(minute) || minute < 0 || minute > 59) return null;
  return { hour, minute };
}

export function parseScheduleIntent(text) {
  const compact = normalizeText(text);
  if (!compact) return { action: 'none' };

  const wantsDaily = /每天|每日|天天/.test(compact);
  const wantsTodoDigest = /(待办|todo|任务).*(记录|列表|清单|安排|摘要)|一天的待办/.test(compact);
  const wantsSend = /发|发送|推送|提醒|通知|给我/.test(compact);
  if (wantsDaily && wantsTodoDigest && wantsSend) {
    const time = parseHourMinute(compact);
    if (!time) {
      return {
        action: 'create_daily_todo_digest',
        needsClarification: ['digest_time'],
      };
    }
    return {
      action: 'create_daily_todo_digest',
      hour: time.hour,
      minute: time.minute,
    };
  }

  if (/看看|查看|看下|列出/.test(compact) && /(待办|日程|行程|计划|任务)/.test(compact)) {
    return { action: 'query_schedule' };
  }

  return { action: 'none' };
}

export function isScheduleIntent(intent) {
  return intent?.action && intent.action !== 'none';
}
