import { DEFAULT_SETTINGS, normalizeSettings } from "./settings.js";

export function parseSettings(input) {
  return normalizeSettings(input || DEFAULT_SETTINGS);
}

export function parseAnalyzePayload(input) {
  const payload = isPlainObject(input) ? input : {};
  return {
    userInstruction: String(payload.userInstruction || "").trim(),
    pageContext: isPlainObject(payload.pageContext) ? payload.pageContext : {},
    includePageContext: payload.includePageContext !== false,
    screenshotDataUrl: String(payload.screenshotDataUrl || ""),
    includeScreenshot: payload.includeScreenshot === true,
    conversationHistory: normalizeConversationHistory(payload.conversationHistory)
  };
}

export function parseStoredSessionRecord(session) {
  if (!isPlainObject(session)) {
    return null;
  }

  if (session.chatSession || session.pageSnapshot) {
    return {
      chatSession: {
        messages: normalizeStoredMessages(session.chatSession?.messages),
        attachmentCache: normalizeAttachmentCache(session.chatSession?.attachmentCache)
      },
      pageSnapshot: isPlainObject(session.pageSnapshot) ? session.pageSnapshot : null
    };
  }

  return {
    chatSession: {
      messages: normalizeStoredMessages(session.messages),
      attachmentCache: normalizeAttachmentCache(session.attachmentCache)
    },
    pageSnapshot: isPlainObject(session.currentContext) ? stripTransportFields(session.currentContext) : null
  };
}

export function normalizeStoredMessages(messages) {
  const normalized = (Array.isArray(messages) ? messages : []).map((message) => ({
    role: message?.role === "assistant" ? "assistant" : "user",
    text: String(message?.text || ""),
    meta: String(message?.meta || ""),
    details: normalizeMessageDetails(message?.details)
  }));

  while (normalized.length) {
    const lastMessage = normalized.at(-1);
    if (lastMessage?.role !== "assistant" || String(lastMessage.text || "").trim()) {
      break;
    }
    normalized.pop();
  }

  return normalized;
}

export function stripTransportFields(context) {
  if (!isPlainObject(context)) {
    return null;
  }
  const clone = { ...context };
  delete clone.screenshotDataUrl;
  delete clone.screenshotMeta;
  return clone;
}

function normalizeConversationHistory(history) {
  return (Array.isArray(history) ? history : []).slice(-8).map((item) => ({
    role: item?.role === "assistant" ? "assistant" : "user",
    text: String(item?.text || "")
  }));
}

function normalizeMessageDetails(details) {
  if (!isPlainObject(details)) {
    return null;
  }
  return {
    contextPreview: String(details.contextPreview || ""),
    screenshotDataUrl: String(details.screenshotDataUrl || ""),
    note: String(details.note || "")
  };
}

function normalizeAttachmentCache(cache) {
  if (!isPlainObject(cache)) {
    return {
      pageContextHash: "",
      screenshotHash: ""
    };
  }

  return {
    pageContextHash: String(cache.pageContextHash || ""),
    screenshotHash: String(cache.screenshotHash || "")
  };
}

function isPlainObject(value) {
  return !!value && typeof value === "object" && !Array.isArray(value);
}
