import {
  readMatrixCliConfig,
  resetMatrixCliConfig,
  resolvePackageRegistry,
  setMatrixCliConfigValue,
  type IMatrixCliConfig,
} from '../utils/config-store.js';

export interface IConfigCommandOptions {
  readonly cwd?: string;
  readonly configPath?: string;
}

export interface IConfigGetResult {
  readonly key: string;
  readonly value: string | undefined;
  readonly source?: 'explicit' | 'env' | 'config' | 'default';
  readonly configPath: string;
}

export interface IConfigListResult {
  readonly configPath: string;
  readonly values: IMatrixCliConfig;
  readonly effective: {
    readonly registry: string;
    readonly registrySource: 'explicit' | 'env' | 'config' | 'default';
  };
}

export interface IConfigSetResult {
  readonly key: string;
  readonly value: string;
  readonly configPath: string;
}

export interface IConfigResetResult {
  readonly configPath: string;
  readonly values: IMatrixCliConfig;
}

function assertSupportedKey(key: string): 'registry' {
  const normalized = key.trim();
  if (normalized !== 'registry') {
    throw new Error(`MX_CONFIG_INVALID: unsupported config key "${key}"`);
  }
  return normalized;
}

export async function configGetCommand(
  key: string,
  options: IConfigCommandOptions = {},
): Promise<IConfigGetResult> {
  const normalizedKey = assertSupportedKey(key);
  const stored = readMatrixCliConfig(options);
  const effective = resolvePackageRegistry(undefined, options);
  return {
    key: normalizedKey,
    value: stored.values.registry ?? effective.registry,
    source: stored.values.registry ? 'config' : effective.source,
    configPath: stored.configPath,
  };
}

export async function configListCommand(options: IConfigCommandOptions = {}): Promise<IConfigListResult> {
  const stored = readMatrixCliConfig(options);
  const effective = resolvePackageRegistry(undefined, options);
  return {
    configPath: stored.configPath,
    values: stored.values,
    effective: {
      registry: effective.registry,
      registrySource: effective.source,
    },
  };
}

export async function configSetCommand(
  key: string,
  value: string,
  options: IConfigCommandOptions = {},
): Promise<IConfigSetResult> {
  const normalizedKey = assertSupportedKey(key);
  const result = setMatrixCliConfigValue(normalizedKey, value, options);
  return {
    key: normalizedKey,
    value: result.values.registry ?? '',
    configPath: result.configPath,
  };
}

export async function configResetCommand(options: IConfigCommandOptions = {}): Promise<IConfigResetResult> {
  return resetMatrixCliConfig(options);
}
