// Lean env config for the zopu server. Read from process.env; no zod dependency.
const required = (key: string): string => {
  const value = process.env[key];
  if (!value) {
    throw new Error(`Missing required env var: ${key}`);
  }
  return value;
};

export interface ServerEnv {
  readonly AGENT_MODEL_PROVIDER: string;
  readonly AGENT_MODEL_NAME: string;
  readonly AGENT_MODEL_API: string;
  readonly AGENT_MODEL_API_KEY: string;
  readonly AGENT_MODEL_BASE_URL: string;
  readonly AGENT_MODEL_CONTEXT_WINDOW: number;
  readonly AGENT_MODEL_MAX_TOKENS: number;
  readonly GITEA_URL: string;
  readonly GITEA_TOKEN: string;
  readonly GIT_REPO: string;
  readonly GIT_SSH_REMOTE: string;
  readonly GIT_DEFAULT_BRANCH: string;
  readonly WORKTREE_ROOT: string;
  readonly PORT: string;
}

export const parseServerEnv = (): ServerEnv => ({
  AGENT_MODEL_API: process.env.AGENT_MODEL_API ?? "openai-completions",
  AGENT_MODEL_API_KEY: required("AGENT_MODEL_API_KEY"),
  AGENT_MODEL_BASE_URL: required("AGENT_MODEL_BASE_URL"),
  AGENT_MODEL_CONTEXT_WINDOW: Number(
    process.env.AGENT_MODEL_CONTEXT_WINDOW ?? 262_000
  ),
  AGENT_MODEL_MAX_TOKENS: Number(process.env.AGENT_MODEL_MAX_TOKENS ?? 131_072),
  AGENT_MODEL_NAME: process.env.AGENT_MODEL_NAME ?? "glm-5.2",
  AGENT_MODEL_PROVIDER: process.env.AGENT_MODEL_PROVIDER ?? "cheaptricks",
  GITEA_TOKEN: process.env.GITEA_TOKEN ?? "",
  GITEA_URL: process.env.GITEA_URL ?? "https://git.openputer.com",
  GIT_DEFAULT_BRANCH: process.env.GIT_DEFAULT_BRANCH ?? "main",
  GIT_REPO: process.env.GIT_REPO ?? "puter/zopu-code",
  GIT_SSH_REMOTE:
    process.env.GIT_SSH_REMOTE ??
    "ssh://git@git.openputer.com:2222/puter/zopu-code.git",
  PORT: process.env.PORT ?? "3590",
  WORKTREE_ROOT: process.env.WORKTREE_ROOT ?? "/tmp/zopu-worktrees",
});
