import { normalizeDisplayText, shortenTitleText, formalizeText } from "./formatters";
import {
  KEYWORD_PATTERNS,
  SUGGESTION_KEYWORDS,
  ACTIVITY_KEYWORDS,
  MUTUAL_AID_KEYWORDS,
  ACTIVITY_REGISTER_KEYWORDS,
  ACTIVITY_LIST_KEYWORDS
} from "../constants";
import { getNavigationByIntent } from "./navigation-map";
import type { DraftMode, ConversationDraft } from "../types";



function containsKeyword(text: string, keywords: string[]) {
  const lower = text.toLowerCase();
  return keywords.some((kw) => lower.includes(kw));
}

export function isSuggestionIntent(text: string) {
  return containsKeyword(text, SUGGESTION_KEYWORDS);
}

export function isActivityIntent(text: string) {
  return containsKeyword(text, ACTIVITY_KEYWORDS);
}

export function isActivityRegisterIntent(text: string) {
  return containsKeyword(text, ACTIVITY_REGISTER_KEYWORDS);
}

export function isMutualAidIntent(text: string) {
  return containsKeyword(text, MUTUAL_AID_KEYWORDS);
}

export function isActivityListIntent(text: string) {
  return containsKeyword(text, ACTIVITY_LIST_KEYWORDS) && !isActivityIntent(text);
}

/**
 * 从消息文本中匹配意图关键词，返回可导航的页面路径
 * 优先匹配新意图（policy_inquiry 等），再匹配 navigation 意图中的页面名
 */
export function getNavigationTarget(message: string): string | null {
  const lower = message.toLowerCase();
  for (const [intent, keywords] of Object.entries(KEYWORD_PATTERNS)) {
    if (intent === "navigation") continue; // navigation 意图单独处理
    if (keywords.some((kw) => lower.includes(kw))) {
      const entry = getNavigationByIntent(intent);
      if (entry) return entry.path;
    }
  }
  // navigation 意图：匹配 "打开XXX"/"跳转XXX" 后跟的页面关键词
  const navMatch = lower.match(/(?:打开|跳转|去|前往)\s*(.+)/);
  if (navMatch) {
    const target = navMatch[1].trim();
    for (const [intent, keywords] of Object.entries(KEYWORD_PATTERNS)) {
      if (intent === "navigation") continue;
      if (keywords.some((kw) => target.includes(kw))) {
        const entry = getNavigationByIntent(intent);
        if (entry) return entry.path;
      }
    }
  }
  return null;
}

export function isShowDraftIntent(text: string) {
  return ["查看草稿", "当前草稿", "看看草稿", "草稿内容"].some((kw) => text.includes(kw));
}

export function isPendingInspectIntent(text: string) {
  return ["待确认", "什么待确认动作", "当前待确认", "查看待确认", "待执行"].some((kw) => text.includes(kw));
}

export function isDraftEditIntent(text: string) {
  return /(标题|摘要|正文|活动标题|活动简介|简介|活动地点|地点|开始时间|结束时间|报名截止|人数上限|互助类型|类型|详情描述|描述|联系电话|联系微信|标签|发布人身份|分会)\s*(改为|改成|换成|换到|改到|调整为|设置为|短一点|短些|简短一点|精简一点|正式一点|更正式|书面一点)/.test(normalizeDisplayText(text));
}

export function detectMutualAidType(text: string): "resource" | "need" | undefined {
  const normalized = normalizeDisplayText(text);
  if (normalized.includes("资源")) return "resource";
  if (normalized.includes("需求")) return "need";
  return undefined;
}

export function extractActivityId(text: string) {
  const matched = text.match(/(?:活动ID|activityId|ID|id|#)\s*[:：]?\s*(\d{1,12})/);
  if (!matched) return 0;
  return Number(matched[1] || 0);
}

export function hasStructuredSuggestionFields(text: string) {
  return /(标题|摘要|正文|分会)\s*[:：]/.test(text);
}

export function hasStructuredActivityFields(text: string) {
  return /(活动标题|标题|活动简介|简介|开始时间|结束时间|活动地点|地点|人数上限|报名截止|分会)\s*[:：]/.test(text);
}

export function hasStructuredMutualAidFields(text: string) {
  return /(互助类型|类型|标题|详情描述|描述|联系电话|联系微信|标签|发布人身份|分会)\s*[:：]/.test(text);
}

export function rewriteDraftEditText(text: string, mode: DraftMode, draft: ConversationDraft) {
  const normalized = normalizeDisplayText(text);
  if (mode === "suggestion") {
    if (/(标题)\s*(短一点|短些|简短一点|精简一点)$/.test(normalized) && draft.suggestion?.title) {
      return "标题：" + shortenTitleText(draft.suggestion.title);
    }
    if (/(摘要)\s*(正式一点|更正式|书面一点)$/.test(normalized) && draft.suggestion?.summary) {
      return "摘要：" + formalizeText(draft.suggestion.summary);
    }
    if (/(正文)\s*(正式一点|更正式|书面一点)$/.test(normalized) && draft.suggestion?.body) {
      return "正文：" + formalizeText(draft.suggestion.body);
    }
  }
  if (mode === "activity") {
    if (/(标题|活动标题)\s*(短一点|短些|简短一点|精简一点)$/.test(normalized) && draft.activity?.title) {
      return "活动标题：" + shortenTitleText(draft.activity.title);
    }
    if (/(活动简介|简介)\s*(正式一点|更正式|书面一点)$/.test(normalized) && draft.activity?.description) {
      return "活动简介：" + formalizeText(draft.activity.description);
    }
  }
  if (mode === "mutualAid") {
    if (/(标题)\s*(短一点|短些|简短一点|精简一点)$/.test(normalized) && draft.mutualAid?.title) {
      return "标题：" + shortenTitleText(draft.mutualAid.title);
    }
    if (/(详情描述|描述)\s*(正式一点|更正式|书面一点)$/.test(normalized) && draft.mutualAid?.description) {
      return "详情描述：" + formalizeText(draft.mutualAid.description);
    }
  }
  const matched = normalized.match(/(标题|摘要|正文|活动标题|活动简介|简介|活动地点|地点|开始时间|结束时间|报名截止|人数上限|互助类型|类型|详情描述|描述|联系电话|联系微信|标签|发布人身份|分会)\s*(改为|改成|换成|换到|改到|调整为|设置为)\s*(.+)$/);
  if (!matched) return normalized;
  let label = matched[1];
  const value = matched[3].trim();
  if (!value) return normalized;
  if (mode === "suggestion") {
    if (label === "标题" || label === "摘要" || label === "正文" || label === "分会") return label + "：" + value;
    return normalized;
  }
  if (mode === "activity") {
    if (label === "标题") label = "活动标题";
    if (label === "简介") label = "活动简介";
    if (label === "地点") label = "活动地点";
    return label + "：" + value;
  }
  if (mode === "mutualAid") {
    if (label === "描述") label = "详情描述";
    return label + "：" + value;
  }
  if (mode === "activityRegister") {
    if (label === "活动ID" || label === "ID") return "活动ID: " + value;
  }
  return normalized;
}

export function extractTopic(text: string, keywords: string[]) {
  let normalized = normalizeDisplayText(text);
  keywords.forEach((kw) => { normalized = normalized.replace(new RegExp(kw, 'g'), ''); });
  normalized = normalized.replace(/[，。、''：:！!？?]/g, ' ').replace(/\s+/g, ' ').trim();
  return normalized || '平台服务';
}
