import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { listen, UnlistenFn } from '@tauri-apps/api/event';
import { getPreset } from '@/lib/presets';
import type {
  AppSettings,
  ByokStatus,
  DirEntry,
  PtyExitEvent,
  PtyOutputEvent,
  PtySpawnOptions,
  VigthoriaAuthStatus,
  VigthoriaHttpResponse,
  WorkbenchUpdateInfo,
  WorkspaceDefinition,
  WorkspacePresetId,
  V4ProviderId,
} from '@/types/workbench';

export async function ptySpawn(options: PtySpawnOptions): Promise<string> {
  return invoke<string>('pty_spawn', { options });
}

export async function ptyWrite(id: string, data: string): Promise<void> {
  return invoke('pty_write', { payload: { id, data } });
}

export async function ptyResize(id: string, cols: number, rows: number): Promise<void> {
  return invoke('pty_resize', { id, cols, rows });
}

export async function ptyKill(id: string): Promise<void> {
  return invoke('pty_kill', { id });
}

export async function workspaceList(): Promise<WorkspaceDefinition[]> {
  return invoke<WorkspaceDefinition[]>('workspace_list');
}

export async function workspaceSave(workspace: WorkspaceDefinition): Promise<WorkspaceDefinition> {
  return invoke<WorkspaceDefinition>('workspace_save', { workspace });
}

export async function workspaceDelete(id: string): Promise<void> {
  return invoke('workspace_delete', { id });
}

export async function settingsGet(): Promise<AppSettings> {
  return invoke<AppSettings>('settings_get');
}

export async function settingsSave(settings: AppSettings): Promise<AppSettings> {
  return invoke<AppSettings>('settings_save', { settings });
}

export async function detectVigthoriaCli(): Promise<string | null> {
  return invoke<string | null>('detect_vigthoria_cli');
}

export async function runVigthoriaUpdate(cliPath?: string): Promise<string> {
  return invoke<string>('run_vigthoria_update', { cliPath: cliPath || null });
}

export async function launchVigthoriaLogin(cliPath?: string): Promise<string> {
  return invoke<string>('launch_vigthoria_login', { cliPath: cliPath || null });
}

export async function vigthoriaLogin(
  email: string,
  password: string,
  cliPath?: string,
): Promise<string> {
  return invoke<string>('vigthoria_login', { cliPath: cliPath || null, email, password });
}

export async function vigthoriaLogout(cliPath?: string): Promise<string> {
  return invoke<string>('vigthoria_logout', { cliPath: cliPath || null });
}

export async function defaultShell(): Promise<string> {
  return invoke<string>('default_shell');
}

export async function platform(): Promise<string> {
  return invoke<string>('platform');
}

export async function appVersion(): Promise<string> {
  return invoke<string>('app_version');
}

export async function checkWorkbenchUpdate(): Promise<WorkbenchUpdateInfo> {
  return invoke<WorkbenchUpdateInfo>('check_workbench_update');
}

export async function downloadWorkbenchUpdate(url: string, sha256: string): Promise<string> {
  return invoke<string>('download_workbench_update', { url, sha256 });
}

export async function installWorkbenchUpdate(path: string): Promise<void> {
  return invoke('install_workbench_update', { path });
}

export async function homeDirectory(): Promise<string> {
  return invoke<string>('home_directory');
}

export async function listDirectory(path: string, limit?: number): Promise<DirEntry[]> {
  return invoke<DirEntry[]>('list_directory', { path, limit });
}

export async function pathExists(path: string): Promise<boolean> {
  return invoke<boolean>('path_exists', { path });
}

export async function isValidProjectRoot(path: string): Promise<boolean> {
  return invoke<boolean>('is_valid_project_root', { path });
}

export async function readWorkspaceFile(
  workspaceRoot: string,
  relativePath: string,
): Promise<string> {
  return invoke<string>('read_workspace_file', {
    workspaceRoot,
    relativePath,
  });
}

export async function writeWorkspaceFile(
  workspaceRoot: string,
  relativePath: string,
  content: string,
  mergeMode: 'overwrite' | 'skip_if_exists' | 'merge_html_body' = 'overwrite',
): Promise<{ path: string; written: boolean; merged: boolean; skipped: boolean }> {
  return invoke('write_workspace_file', {
    payload: {
      workspaceRoot,
      relativePath,
      content,
      mergeMode,
    },
  });
}

export async function runWorkspaceStabilizeSandbox(
  rootPath: string,
): Promise<{ success: boolean; output: string }> {
  return invoke<{ success: boolean; output: string }>('run_workspace_stabilize_sandbox_cmd', {
    rootPath,
  });
}

export async function runWorkspaceStabilize(
  rootPath: string,
): Promise<{ success: boolean; output: string }> {
  return invoke<{ success: boolean; output: string }>('run_workspace_stabilize_cmd', {
    rootPath,
  });
}

export async function packageStartCommand(rootPath: string): Promise<string | null> {
  return invoke<string | null>('package_start_command', { rootPath });
}

export async function vigthoriaAuthStatus(verify = true): Promise<VigthoriaAuthStatus> {
  return invoke<VigthoriaAuthStatus>('vigthoria_auth_status', { verify });
}

export async function vigthoriaAuthToken(): Promise<string | null> {
  return invoke<string | null>('vigthoria_auth_token');
}

export async function vigthoriaHttpProxy(
  method: string,
  url: string,
  token?: string | null,
  body?: string | null,
): Promise<VigthoriaHttpResponse> {
  return invoke<VigthoriaHttpResponse>('vigthoria_http_proxy', {
    method,
    url,
    token: token ?? null,
    body: body ?? null,
  });
}

export async function getByokStatus(): Promise<ByokStatus> {
  return invoke<ByokStatus>('get_byok_status');
}

export async function setByokConfig(
  apiKey: string | null,
  baseUrl: string,
  model: string,
  clearApiKey = false,
): Promise<ByokStatus> {
  return invoke<ByokStatus>('set_byok_config', {
    apiKey: apiKey && apiKey.trim() ? apiKey.trim() : null,
    baseUrl,
    model,
    clearApiKey,
  });
}

export async function pickDirectory(defaultPath?: string): Promise<string | null> {
  const selected = await open({
    directory: true,
    multiple: false,
    defaultPath,
  });
  if (typeof selected === 'string') return selected;
  return null;
}

export function onPtyOutput(handler: (event: PtyOutputEvent) => void): Promise<UnlistenFn> {
  return listen<PtyOutputEvent>('pty-output', (event) => handler(event.payload));
}

export function onPtyExit(handler: (event: PtyExitEvent) => void): Promise<UnlistenFn> {
  return listen<PtyExitEvent>('pty-exit', (event) => handler(event.payload));
}

export function buildVigthoriaEnv(
  workspaceRoot: string,
  settings: WorkspaceDefinition['vigthoria'],
  appSettings?: AppSettings,
): Record<string, string> {
  const env: Record<string, string> = {
    VIGTHORIA_NO_SESSION_MENU: '1',
    VIGTHORIA_WORKSPACE: workspaceRoot,
    VIGTHORIA_DEBUG: settings.debugMode ? '1' : '0',
    VIGTHORIA_AUTO_APPROVE: settings.autoApprove ? '1' : '0',
    VIGTHORIA_AUTO_SAVE: settings.autoSave ? '1' : '0',
    VIGTHORIA_DECK_MODE: '1',
  };
  const cliPath = settings.cliPath || appSettings?.vigthoriaCliPath;
  if (cliPath) {
    env.VIGTHORIA_CLI_PATH = cliPath;
  }
  return env;
}

export function createWorkspaceFromPreset(
  presetId: WorkspacePresetId,
  name: string,
  rootPath: string,
  options?: { v4Provider?: V4ProviderId },
): WorkspaceDefinition {
  return getPreset(presetId).build(name, rootPath, options);
}
