import {
  DEFAULT_SETTINGS
} from "./shared/settings.js";
import { recordDiagnostic } from "./shared/diagnostics.js";
import { MESSAGE_TYPES, PORT_NAMES } from "./shared/message-types.js";
import { analyzeRequest, analyzeRequestStream } from "./background/services/ai-client.js";
import { getStoredSettings, saveStoredSettings } from "./background/services/settings-store.js";

chrome.runtime.onInstalled.addListener(async () => {
  await saveStoredSettings(await getStoredSettings());
});

chrome.sidePanel
  .setPanelBehavior({ openPanelOnActionClick: true })
  .catch((error) => console.error("Failed to set side panel behavior", error));

chrome.runtime.onConnect.addListener((port) => {
  if (port.name !== PORT_NAMES.ANALYZE_STREAM) {
    return;
  }

  const controller = new AbortController();
  let active = true;

  const cleanup = () => {
    if (!active) {
      return;
    }
    active = false;
    try {
      controller.abort();
    } catch (error) {
      // Ignore abort errors.
    }
  };

  port.onDisconnect.addListener(cleanup);

  port.onMessage.addListener(async (message) => {
    if (message?.type === MESSAGE_TYPES.ANALYZE_STREAM_PING) {
      return;
    }

    if (message?.type !== MESSAGE_TYPES.ANALYZE_STREAM_START) {
      return;
    }

    try {
      const result = await analyzeRequestStream(message.payload || {}, {
        signal: controller.signal,
        onDelta(delta) {
          port.postMessage({
            type: MESSAGE_TYPES.ANALYZE_STREAM_DELTA,
            delta
          });
        }
      });

      if (active) {
        await recordDiagnostic({
          source: "background",
          event: "stream_completed",
          details: {
            model: result.model || "",
            hasUsage: !!result.usage
          }
        });
        port.postMessage({
          type: MESSAGE_TYPES.ANALYZE_STREAM_DONE,
          result
        });
      }
    } catch (error) {
      if (active) {
        await recordDiagnostic({
          source: "background",
          event: "stream_failed",
          details: error instanceof Error ? error.message : String(error)
        });
        port.postMessage({
          type: MESSAGE_TYPES.ANALYZE_STREAM_ERROR,
          error: error instanceof Error ? error.message : String(error)
        });
      }
    }
  });
});

chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  if (message?.type === MESSAGE_TYPES.GET_SETTINGS) {
    getStoredSettings()
      .then((settings) => sendResponse({ ok: true, settings }))
      .catch((error) =>
        sendResponse({
          ok: false,
          error: error instanceof Error ? error.message : String(error)
        })
      );
    return true;
  }

  if (message?.type === MESSAGE_TYPES.SAVE_SETTINGS) {
    saveStoredSettings(message.payload || {})
      .then(() => sendResponse({ ok: true }))
      .catch((error) =>
        sendResponse({
          ok: false,
          error: error instanceof Error ? error.message : String(error)
        })
      );
    return true;
  }

  if (message?.type === MESSAGE_TYPES.ANALYZE) {
    analyzeRequest(message.payload || {})
      .then((result) => sendResponse({ ok: true, result }))
      .catch((error) =>
        sendResponse({
          ok: false,
          error: error instanceof Error ? error.message : String(error)
        })
      );
    return true;
  }

  return false;
});
