// @ts-nocheck
import { useAppConfig } from './appConfig';
import { isPreviewRuntime } from './previewRuntime';
import { getOrCreateClientId } from './clientIdentity';
import {
  createNotificationMessage,
  sendClientNotification,
  shouldFallbackToLocalNotification,
  showLocalClientNotification,
} from './notificationApi';
import { chatGateway } from './chatV2';
import { resolveChatPathForSession } from './chatSessionRouting';
import type { ChatConversationRequest, ChatMessage } from './mainChatPanel/types';

const MAX_NOTIFICATION_DETAIL_POLLS = 3;

function createConversationPreviewText(text: string) {
  const normalized = String(text ?? '').replace(/\s+/g, ' ').trim();
  return normalized.length > 140 ? `${normalized.slice(0, 137).trimEnd()}...` : normalized;
}

function createChatQuestionAnswerNotificationBody(args: {
  questionText?: string | null;
  answerText?: string | null;
  fallback: string;
}) {
  const questionPreview = createConversationPreviewText(args.questionText ?? '');
  const answerPreview = createConversationPreviewText(args.answerText ?? '');

  if (questionPreview && answerPreview) {
    return `질문: ${questionPreview}\n답변: ${answerPreview}`;
  }

  if (answerPreview) {
    return `답변: ${answerPreview}`;
  }

  if (questionPreview) {
    return `질문: ${questionPreview}`;
  }

  return args.fallback;
}

function createChatQuestionOnlyNotificationPreview(questionText?: string | null, fallback?: string) {
  const questionPreview = createConversationPreviewText(questionText ?? '');
  return questionPreview ? `질문: ${questionPreview}` : fallback ?? '';
}

function normalizeNotificationDetailText(text?: string | null) {
  const normalized = String(text ?? '').trim();
  return normalized || undefined;
}

function buildChatNotificationLink(sessionId: string) {
  const normalizedSessionId = sessionId.trim();

  if (!normalizedSessionId || typeof window === 'undefined') {
    return '';
  }

  const targetUrl = new URL(resolveChatPathForSession(normalizedSessionId), window.location.origin);
  targetUrl.searchParams.set('topMenu', 'chat');
  targetUrl.searchParams.set('sessionId', normalizedSessionId);
  return targetUrl.toString();
}

async function tryShowLocalChatNotification(args: {
  title: string;
  body: string;
  threadId: string;
  data: Record<string, string>;
}) {
  if (shouldSuppressChatNotificationWhenAppOpen()) {
    return;
  }

  await showLocalClientNotification({
    title: args.title,
    body: args.body,
    threadId: args.threadId,
    data: args.data,
  }).catch(() => false);
}

function findLatestCodexMessage(messages: ChatMessage[]) {
  for (let index = messages.length - 1; index >= 0; index -= 1) {
    const candidate = messages[index];

    if (candidate.author === 'codex') {
      return candidate;
    }
  }

  return null;
}

function findQuestionText(messages: ChatMessage[], requestId?: string | null) {
  if (!requestId) {
    return '';
  }

  for (let index = messages.length - 1; index >= 0; index -= 1) {
    const candidate = messages[index];

    if (candidate.author !== 'user' || candidate.clientRequestId !== requestId) {
      continue;
    }

    return candidate.text;
  }

  return '';
}

function findLatestFailedRequest(requests: ChatConversationRequest[]) {
  for (let index = requests.length - 1; index >= 0; index -= 1) {
    const candidate = requests[index];

    if (candidate.status === 'failed') {
      return candidate;
    }
  }

  return null;
}

function shouldNotifyWhileAway() {
  if (typeof document === 'undefined') {
    return true;
  }

  if (document.visibilityState === 'hidden') {
    return true;
  }

  if (typeof document.hasFocus === 'function') {
    return !document.hasFocus();
  }

  return false;
}

function shouldPollConversationNotifications() {
  if (typeof document === 'undefined') {
    return true;
  }

  if (document.visibilityState === 'hidden') {
    return true;
  }

  if (typeof document.hasFocus === 'function') {
    return !document.hasFocus();
  }

  return false;
}

function shouldSuppressChatNotificationWhenAppOpen() {
  if (typeof window === 'undefined' || typeof document === 'undefined') {
    return false;
  }

  if (document.visibilityState === 'hidden') {
    return false;
  }

  if (typeof document.hasFocus === 'function') {
    return document.hasFocus();
  }

  return true;
}

function getConversationActivityTime(item: { lastMessageAt?: string | null; updatedAt?: string | null }) {
  const candidate = item.lastMessageAt || item.updatedAt || '';
  const parsed = candidate ? Date.parse(candidate) : Number.NaN;
  return Number.isNaN(parsed) ? 0 : parsed;
}

function selectNotificationPollingCandidates<
  T extends {
    notifyOffline: boolean;
    hasUnreadResponse: boolean;
    currentJobStatus: string | null;
    currentRequestId: string | null;
    lastMessageAt: string | null;
    updatedAt: string;
  },
>(items: T[]) {
  return items
    .filter((item) => item.notifyOffline === true)
    .filter((item) => item.hasUnreadResponse || item.currentJobStatus === 'started' || item.currentJobStatus === 'queued' || item.currentRequestId)
    .sort((left, right) => getConversationActivityTime(right) - getConversationActivityTime(left))
    .slice(0, MAX_NOTIFICATION_DETAIL_POLLS);
}

export function ChatNotificationBridgeV2() {
  const appConfig = useAppConfig();

  if (isPreviewRuntime() || !appConfig.chat.receiveRoomNotifications) {
    return null;
  }

  return null;
}
