import { characterState } from "$lib/stores/character";
import { notificationManager } from "./notificationManager";
import type { CharacterState } from "$lib/types/states";
import type { ConnectionStatus } from "$lib/types/messages";

// Track previous states to detect transitions
let previousCharacterState: CharacterState | null = null;
let previousConnectionStatus: ConnectionStatus | null = null;
let taskStartTime: number | null = null;
let hasNotifiedTaskStart = false;

export function handleCharacterStateChange(newState: CharacterState): void {
  // Detect state transitions
  if (previousCharacterState === newState) return;

  // Task completion: any state -> success
  if (newState === "success" && previousCharacterState !== null) {
    const taskDuration = taskStartTime ? Date.now() - taskStartTime : 0;
    // Only notify for tasks that took more than 2 seconds
    if (taskDuration > 2000) {
      notificationManager.notifySuccess();
    }
    taskStartTime = null;
  }

  // Error occurred
  if (newState === "error" && previousCharacterState !== "error") {
    notificationManager.notifyError();
  }

  // Permission needed
  if (newState === "permission") {
    notificationManager.notifyPermission();
  }

  // Starting long tasks - only notify once per response
  if (
    (newState === "coding" || newState === "searching") &&
    previousCharacterState !== "coding" &&
    previousCharacterState !== "searching" &&
    !hasNotifiedTaskStart
  ) {
    taskStartTime = Date.now();
    hasNotifiedTaskStart = true;
    notificationManager.notifyTaskStart();
  }

  previousCharacterState = newState;
}

export function handleConnectionStatusChange(newStatus: ConnectionStatus): void {
  // Only notify on successful connection after being disconnected
  if (
    newStatus === "connected" &&
    previousConnectionStatus &&
    previousConnectionStatus !== "connected"
  ) {
    notificationManager.notifyConnection();
  }

  previousConnectionStatus = newStatus;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function handleToolExecution(_toolName: string): void {
  // For now, we don't notify on every tool execution
  // But we could add specific rules here if needed
}

// Reset notification state for a new response
export function handleNewUserMessage(): void {
  hasNotifiedTaskStart = false;
}

// Store unsubscribe functions
let unsubscribeCharacterState: (() => void) | null = null;

// Initialize listeners
export function initializeNotificationRules(): void {
  // Clean up any existing subscriptions first
  cleanupNotificationRules();

  // Subscribe to character state changes
  unsubscribeCharacterState = characterState.subscribe((state) => {
    handleCharacterStateChange(state);
  });

  // We'll connect to connection status in the next step
}

// Cleanup function to prevent duplicate listeners
export function cleanupNotificationRules(): void {
  if (unsubscribeCharacterState) {
    unsubscribeCharacterState();
    unsubscribeCharacterState = null;
  }

  // Reset state tracking
  previousCharacterState = null;
  previousConnectionStatus = null;
  taskStartTime = null;
  hasNotifiedTaskStart = false;
}
