import type { ThemeId, ThemeModeId } from "#cli/core/theme";
import type { StoreState } from "./state";
import { prefixedEnvKeys } from "#cli/core/env";
import { normalizeThemeId } from "#cli/core/theme";

export function createContextActions(state: StoreState): Readonly<{
  setFocusFiles: (files: readonly string[] | undefined) => void;
  setCwd: (cwd: string) => void;
  setEnvVar: (key: string, value: string | undefined) => void;
  setAgent: (agentName: string | undefined) => void;
  setThemeMode: (mode: ThemeModeId | ThemeId) => void;
}> {
  function setFocusFiles(files: readonly string[] | undefined): void {
    const ctx = state.context;
    const next = (files ?? []).map((f) => String(f ?? "")).filter(Boolean);
    state.context = { ...ctx, focusFiles: next.length ? next : undefined };
  }

  function setCwd(cwd: string): void {
    const ctx = state.context;
    const next = String(cwd ?? "").trim() || ".";
    state.context = { ...ctx, cwd: next };
  }

  function setEnvVar(key: string, value: string | undefined): void {
    const ctx = state.context;
    const prevEnv = { ...ctx.env } as Record<string, string | undefined>;
    const k = String(key ?? "").trim();
    if (!k) return;
    const v = value == null ? "" : String(value);
    if (!v) delete prevEnv[k];
    else prevEnv[k] = v;
    state.context = { ...ctx, env: prevEnv };

    if (typeof process !== "undefined" && process?.env) {
      if (v) process.env[k] = v;
      else delete process.env[k];
    }
  }

  function setAgent(agentName: string | undefined): void {
    const v = agentName == null ? undefined : String(agentName);
    for (const key of prefixedEnvKeys("AGENT")) setEnvVar(key, v);
  }

  function setThemeMode(mode: ThemeModeId | ThemeId): void {
    const next = normalizeThemeId(mode);
    state.ui.theme.mode = next;
    for (const key of prefixedEnvKeys("THEME")) setEnvVar(key, next);
  }

  return {
    setFocusFiles,
    setCwd,
    setEnvVar,
    setAgent,
    setThemeMode,
  };
}
