import { BrowserWindow, Menu, app, nativeImage, shell } from "electron";
import path from "node:path";
import { AgentRunner } from "./agent/runner";
import { LogStore } from "./agent/logStore";
import { AssistantOrchestrator } from "./assistant/assistantOrchestrator";
import { SmqjhClient } from "./cloud/smqjhClient";
import { SessionState } from "./cloud/session";
import { SessionStore } from "./cloud/sessionStore";
import { ConfigStore } from "./config/appConfig";
import { ReadOnlyDatabaseClient } from "./db/readOnlyDatabase";
import { DeepSeekClient } from "./deepseek/deepSeekClient";
import { registerIpc } from "./ipc/registerIpc";
import { McpClient } from "./mcp/mcpClient";

const APP_ID = "com.smqjh.admin.agent";

let mainWindow: BrowserWindow | undefined;

async function createWindow(): Promise<void> {
  Menu.setApplicationMenu(null);

  const configStore = new ConfigStore();
  await configStore.load();

  const logStore = new LogStore();
  const sessionStore = new SessionStore();
  const session = new SessionState();
  const persistedSession = await sessionStore.load();
  if (persistedSession) {
    session.restore(persistedSession);
  }

  const client = new SmqjhClient(() => configStore.get(), session, sessionStore);
  await client.ensureSessionFresh().catch((error) => {
    logStore.add("warn", "Persisted session refresh failed", {
      message: error instanceof Error ? error.message : String(error)
    });
  });
  const database = new ReadOnlyDatabaseClient(() => configStore.get());
  const deepSeekClient = new DeepSeekClient(() => configStore.get());
  const mcpClient = new McpClient(() => configStore.get());
  const appIcon = nativeImage.createFromPath(path.join(app.getAppPath(), "build", "icon.png"));

  mainWindow = new BrowserWindow({
    width: 1240,
    height: 820,
    minWidth: 1080,
    minHeight: 700,
    title: "市民请集合智能助手",
    icon: appIcon.isEmpty() ? path.join(app.getAppPath(), "build", "icon.ico") : appIcon,
    backgroundColor: "#f6f7f9",
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.join(__dirname, "preload.js")
    }
  });

  const runner = new AgentRunner({
    client,
    database,
    configStore,
    logStore,
    getWebContents: () => mainWindow?.webContents
  });
  const assistantOrchestrator = new AssistantOrchestrator({
    mcpClient,
    runner,
    logStore
  });

  registerIpc({ configStore, logStore, runner, client, session, deepSeekClient, assistantOrchestrator, mcpClient });

  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url);
    return { action: "deny" };
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    await mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
    mainWindow.webContents.openDevTools({ mode: "detach" });
  } else {
    await mainWindow.loadFile(path.join(__dirname, "../../renderer/index.html"));
  }

  logStore.add("info", "市民请集合智能助手已启动");
}

if (process.platform === "win32") {
  app.setAppUserModelId(APP_ID);
}

app.whenReady().then(createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    void createWindow();
  }
});
