/**
 * Thin wrapper around @kubernetes/client-node.
 *
 * Centralises KubeConfig loading (in-cluster or kubeconfig) and exposes
 * the typed API clients the KubernetesOrchestrator needs.
 */
import * as k8s from '@kubernetes/client-node';

export interface K8sOfficialClientConfig {
  /** Override the namespace for MCP server pods. Defaults to 'mcpctl-servers'. */
  serversNamespace?: string;
  /**
   * Explicit kubeconfig context name. When set, the client switches to this
   * context before creating API clients — prevents accidental operations
   * against the wrong cluster.  Env: MCPD_K8S_CONTEXT.
   */
  context?: string;
}

export class K8sOfficialClient {
  readonly kc: k8s.KubeConfig;
  readonly core: k8s.CoreV1Api;
  readonly exec: k8s.Exec;
  readonly attach: k8s.Attach;
  readonly log: k8s.Log;
  readonly serversNamespace: string;

  constructor(opts?: K8sOfficialClientConfig) {
    this.kc = new k8s.KubeConfig();
    this.kc.loadFromDefault();

    // Enforce explicit context if configured — safety against multi-cluster mishaps
    const ctx = opts?.context ?? process.env['MCPD_K8S_CONTEXT'];
    if (ctx) {
      this.kc.setCurrentContext(ctx);
    }

    this.core = this.kc.makeApiClient(k8s.CoreV1Api);
    this.exec = new k8s.Exec(this.kc);
    this.attach = new k8s.Attach(this.kc);
    this.log = new k8s.Log(this.kc);
    this.serversNamespace = opts?.serversNamespace
      ?? process.env['MCPD_SERVERS_NAMESPACE']
      ?? 'mcpctl-servers';
  }

  /** Current namespace from in-cluster config, or 'default'. */
  get controlNamespace(): string {
    const contexts = this.kc.getContexts();
    const current = this.kc.getCurrentContext();
    const ctxObj = contexts.find((c) => c.name === current);
    return ctxObj?.namespace ?? 'default';
  }
}
