import { parseJsonLike, type AgentConversation, type AgentConversationMessage, type AgentModelOption } from "../../../api/agent";
import type { ChatMessage, ConversationItem, PendingAction, UserBranch } from "../types";
import { UI_TEXT, SUGGESTION_KEYWORDS, ACTIVITY_KEYWORDS, MUTUAL_AID_KEYWORDS } from "../constants";

export function shortTime(date = new Date()) {
  return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}

export function safeText(text: unknown) {
  return String(text || "").replace(/\\u([0-9a-fA-F]{4})/g, (_, code) => String.fromCharCode(parseInt(code, 16)));
}

export function normalizeDisplayText(text: unknown, fallback = "") {
  const value = safeText(text).replace(/\r/g, "").trim();
  if (!value) return fallback;
  return value;
}

export function toMessageId(prefix: string, seed: string | number) {
  return `${prefix}-${String(seed)}`;
}

export function emptyDraft() {
  return { mode: "none" as const }
}

export function normalizeConversation(item: AgentConversation): ConversationItem {
  return {
    id: Number(item.id),
    title: normalizeDisplayText(item.title, "新会话"),
    summary: normalizeDisplayText(item.summary, UI_TEXT.noConversationSummary),
    updatedAt: normalizeDisplayText(item.updatedAt, shortTime()),
    modelCode: String(item.modelCode || "")
  };
}

export function normalizeConversationMessage(item: AgentConversationMessage): ChatMessage {
  const toolName = normalizeDisplayText(item.toolName || item.tool_name || "");
  const toolStatus = normalizeDisplayText(item.toolStatus || item.tool_status || "");
  const displayPayload = normalizeToolDisplayPayload(normalizeMessageDisplayPayload(item));
  const content = normalizeDisplayText(item.content, "");
  const isToolMessage = item.role !== "user" && Boolean(toolName);
  const text = isToolMessage
    ? normalizeDisplayText(content || displayPayload.summary || displayPayload.message, toolName ? `${toolName} 已返回结果` : "")
    : content;
  const targetId = Number(displayPayload.activityId || displayPayload.postId || displayPayload.serviceProjectId || displayPayload.id || 0);
  const refId = String(displayPayload.id || displayPayload.contentId || displayPayload.activityId || displayPayload.postId || "").trim();
  return {
    id: toMessageId("server", item.id || item.messageIndex || Date.now()),
    messageId: Number(item.id || 0) || undefined,
    role: item.role === "user" ? "user" : "assistant",
    text,
    time: shortTime(new Date(item.createdAt || item.created_at || Date.now())),
    actions: isToolMessage ? actionButtonsForResult(toolName, displayPayload, refId, targetId > 0 ? targetId : undefined) : undefined,
    draftLines: isToolMessage ? displayPayloadPreviewLines(displayPayload) : undefined,
    variant: isToolMessage ? variantFromToolStatus(toolStatus) : undefined,
    pageTarget: normalizeDisplayText(displayPayload.relatedPage || displayPayload.pageTarget || ""),
    feedbackRating: item.feedbackRating || item.feedback_rating || ""
  };
}

function normalizeMessageDisplayPayload(item: AgentConversationMessage): Record<string, any> {
  if (item.displayPayload && typeof item.displayPayload === "object") {
    return item.displayPayload as Record<string, any>;
  }
  return parseJsonLike<Record<string, any>>(item.displayPayloadJson || item.display_payload_json, {});
}

function normalizeToolDisplayPayload(raw: Record<string, any>) {
  const payload = raw && typeof raw.payload === "object" && !Array.isArray(raw.payload) ? raw.payload : {};
  const result = payload && typeof payload.result === "object" && !Array.isArray(payload.result) ? payload.result : {};
  return {
    ...raw,
    ...payload,
    ...result,
    actionRequestId: raw.actionRequestId || payload.actionRequestId || result.actionRequestId,
    displayName: raw.displayName || payload.displayName || result.displayName,
    summary: raw.summary || payload.summary || result.summary
  };
}

function variantFromToolStatus(status: string): ChatMessage["variant"] {
  const normalized = status.toLowerCase();
  if (normalized === "succeeded" || normalized === "success" || normalized === "executed") {
    return "success";
  }
  if (normalized.includes("pending") || normalized === "approved" || normalized === "executing") {
    return "pending";
  }
  return "default";
}

function displayPayloadPreviewLines(payload: Record<string, any>) {
  const summary = normalizeDisplayText(payload.summary || payload.message || "");
  if (summary) {
    return previewLinesFromText(summary).slice(0, 8);
  }
  const items = Array.isArray(payload.items)
    ? payload.items
    : Array.isArray(payload.publicActivities)
      ? payload.publicActivities
      : [];
  if (items.length > 0) {
    return items.slice(0, 5).map((item: any, index: number) => {
      const title = normalizeDisplayText(item?.title || item?.name || `结果${index + 1}`);
      const status = normalizeDisplayText(item?.status || item?.registrationStatus || "");
      return `${index + 1}. ${status ? `${title}（${status}）` : title}`;
    });
  }
  return undefined;
}

export function roleLabelFromMe(me: any) {
  const roles: string[] = Array.isArray(me?.roles) ? me.roles.map((x: any) => String(x || "")) : [];
  if (roles.includes("PLATFORM_ADMIN")) return "平台管理员";
  if (roles.includes("CITY_ADMIN")) return "市级管理员";
  if (roles.includes("BRANCH_ADMIN")) return "分会管理员";
  if (me?.member) return "会员用户";
  if (me?.id) return "已登录用户";
  return "游客";
}

export function parseUserBranchesFromMe(me: any): UserBranch[] {
  const candidates: any[] = [];
  if (Array.isArray(me?.branches)) candidates.push(...me.branches);
  if (Array.isArray(me?.member?.branches)) candidates.push(...me.member.branches);
  if (Array.isArray(me?.memberBranches)) candidates.push(...me.memberBranches);
  const map = new Map<number, string>();
  candidates.forEach((row) => {
    const id = Number(row?.id || row?.branchId || 0);
    const name = normalizeDisplayText(row?.name || row?.branchName || "");
    if (id > 0 && name) map.set(id, name);
  });
  return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
}

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

export function parseDateToOffset(raw: string) {
  const text = normalizeDisplayText(raw).split(".").join("-").replace(/\//g, "-");
  const match = text.match(/(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})/);
  if (!match) return "";
  return `${match[1]}T${match[2]}:00+08:00`;
}

export function toTimestamp(text?: string) {
  if (!text) return 0;
  const normalized = text.replace("+08:00", "").replace("T", " ");
  const safe = normalized.length === 16 ? `${normalized}:00` : normalized;
  const value = Date.parse(safe.replace(" ", "T") + "+08:00");
  return Number.isFinite(value) ? value : 0;
}

export function parseFirstNumber(text: string) {
  const match = normalizeDisplayText(text).match(/\d+/);
  return match ? Number(match[0]) : 0;
}

export function pickKV(line: string) {
  const idx = line.search(/[:：]/);
  if (idx < 0) return null;
  const key = line.slice(0, idx).trim();
  const value = line.slice(idx + 1).trim();
  if (!key || !value) return null;
  return { key, value };
}

export function shortenTitleText(text: string) {
  let next = normalizeDisplayText(text)
    .replace("方面的建言", "建言")
    .replace("主题活动", "活动")
    .replace("资源发布", "资源")
    .replace("需求发布", "需求")
    .trim();
  if (next.length > 12) next = `${next.slice(0, 12)}`;
  return next || normalizeDisplayText(text);
}

export function formalizeText(text: string) {
  let next = normalizeDisplayText(text)
    .replace(/[!！]{2,}/g, "。")
    .replace(/[?？]{2,}/g, "。")
    .replace(/[啊呀吧呢嘛]+$/g, "")
    .replace(/\s+/g, "");
  if (next && !/[。！？]$/.test(next)) next = `${next}。`;
  return next || normalizeDisplayText(text);
}

export function mutualAidTypeText(postType?: "resource" | "need") {
  if (postType === "resource") return "资源";
  if (postType === "need") return "需求";
  return "（未填写）";
}

export function previewLinesFromText(text: string) {
  return text.split("\n").map((line) => line.trim()).filter(Boolean);
}

export function suggestionPreview(draft: { title?: string; summary?: string; body?: string; branchName?: string }) {
  return [
    `标题：${draft.title || "（未填写）"}`,
    `摘要：${draft.summary || "（未填写）"}`,
    `正文：${draft.body || "（未填写）"}`,
    `分会：${draft.branchName || "（未填写）"}`
  ].join("\n");
}

export function activityPreview(draft: { title?: string; description?: string; location?: string; startsAt?: string; endsAt?: string; registerDeadline?: string; capacity?: number; branchName?: string }) {
  return [
    `活动标题：${draft.title || "（未填写）"}`,
    `活动简介：${draft.description || "（未填写）"}`,
    `活动地点：${draft.location || "（未填写）"}`,
    `开始时间：${draft.startsAt || "（未填写）"}`,
    `结束时间：${draft.endsAt || "（未填写）"}`,
    `报名截止：${draft.registerDeadline || "（可选，未填写）"}`,
    `人数上限：${draft.capacity || "（可选，未填写）"}`,
    `分会：${draft.branchName || "（未填写）"}`
  ].join("\n");
}

export function mutualAidPreview(draft: { postType?: "resource" | "need"; title?: string; description?: string; contactPhone?: string; contactWechat?: string; tagsText?: string; publisherTitle?: string; branchName?: string }) {
  return [
    `互助类型：${mutualAidTypeText(draft.postType)}`,
    `标题：${draft.title || "（未填写）"}`,
    `详情描述：${draft.description || "（未填写）"}`,
    `联系电话：${draft.contactPhone || "（可选，未填写）"}`,
    `联系微信：${draft.contactWechat || "（可选，未填写）"}`,
    `标签：${draft.tagsText || "（可选，未填写）"}`,
    `发布人身份：${draft.publisherTitle || "（可选，未填写）"}`,
    `分会：${draft.branchName || "（未填写）"}`
  ].join("\n");
}

export function activityRegisterPreview(draft: { activityId?: number; title?: string; startsAt?: string; location?: string }) {
  return [
    `活动ID：${draft.activityId || "未识别"}`,
    `活动标题：${draft.title || "未命名活动"}`,
    `开始时间：${draft.startsAt || "未提供"}`,
    `活动地点：${draft.location || "未提供"}`
  ].join("\n");
}

export function activityListItemPreview(item: Record<string, any>, index: number) {
  const title = normalizeDisplayText(item?.title || item?.name || `活动${index + 1}`);
  const startsAt = normalizeDisplayText(item?.startsAt || item?.starts_at || item?.startTime || "", "未提供");
  const location = normalizeDisplayText(item?.location || item?.address || "", "未提供");
  return [
    `${index + 1}. ${title}`,
    `   时间：${startsAt}`,
    `   地点：${location}`
  ].join("\n");
}

export function buildFallbackReply(userText: string, actor: string) {
  const suggestion = UI_TEXT.fallbackPrompts[Math.floor(Math.random() * UI_TEXT.fallbackPrompts.length)];
  return `收到，${actor}。你这次提到"${userText}"，我可以继续帮你处理，也可以先从"${suggestion}"开始。`;
}

export function formatActionResult(actionCode: string, result: Record<string, unknown> | undefined, payload?: Record<string, unknown>) {
  const title = normalizeDisplayText(result?.title || payload?.title || "");
  const id = String(result?.id || result?.contentId || result?.activityId || result?.postId || "").trim();
  if (actionCode === "content.suggestion.submit") {
    return `建言已提交成功${id ? `（ID: ${id}）` : ""}。\n标题：${title || "未命名建言"}\n当前状态：待审核`;
  }
  if (actionCode === "activity.submit_for_review") {
    return `活动已提交审核${id ? `（ID: ${id}）` : ""}。\n标题：${title || "未命名活动"}\n下一步：可前往"我的-我发布的活动"查看审核进度。`;
  }
  if (actionCode === "mutual_aid.post.submit") {
    return `企业互助已提交${id ? `（ID: ${id}）` : ""}。\n标题：${title || "未命名互助"}\n下一步：可前往"我的-企业互助"查看审核进度。`;
  }
  if (actionCode === "activity.register.submit") {
    return `活动报名成功${id ? `（活动ID: ${id}）` : ""}。\n活动标题：${title || "目标活动"}\n下一步：可前往"我的-我报名的活动"查看。`;
  }
  if (actionCode === "activity.list_visible") {
    return "我已经为你查询了公开活动。";
  }
  return "动作已执行完成。";
}

export function actionButtonsForResult(actionCode: string, payload?: Record<string, unknown>, refId?: string, targetId?: number) {
  if (actionCode === "content.suggestion.submit") {
    return [{ label: "查看我的建言", action: refId ? `goto_my_suggestions:${refId}` : "goto_my_suggestions" }];
  }
  if (actionCode === "activity.submit_for_review") {
    const activityId = refId || (targetId ? String(targetId) : "");
    return [{ label: "查看我发布的活动", action: activityId ? `goto_my_created_activities:${activityId}` : "goto_my_created_activities" }];
  }
  if (actionCode === "mutual_aid.post.submit") {
    const postType = String(payload?.postType || "").trim();
    return [
      {
        label: postType === "need" ? "查看我的需求" : "查看我的资源",
        action: postType === "need"
          ? (refId ? `goto_my_mutual_aid_needs:${refId}` : "goto_my_mutual_aid_needs")
          : (refId ? `goto_my_mutual_aid_resources:${refId}` : "goto_my_mutual_aid_resources")
      }
    ];
  }
  if (actionCode === "activity.register.submit") {
    const activityId = refId || (targetId ? String(targetId) : "");
    return [{ label: "查看我报名的活动", action: activityId ? `goto_my_registered_activities:${activityId}` : "goto_my_registered_activities" }];
  }
  return [];
}

export function buildPendingDescription(pending: PendingAction | null) {
  if (!pending) return "当前没有待确认动作。";
  const labelMap: Record<string, string> = {
    "content.suggestion.submit": "提交建言",
    "activity.create_draft": "创建活动草稿",
    "activity.submit_for_review": "提交活动审核",
    "mutual_aid.post.submit": "提交企业互助",
    "activity.register.submit": "提交活动报名"
  };
  return [`待确认动作：${labelMap[pending.actionCode] || pending.actionCode}`, pending.previewText || ""].filter(Boolean).join("\n");
}
