import yaml from 'js-yaml';

export type OutputFormat = 'table' | 'json' | 'yaml';

export function formatJson(data: unknown): string {
  return JSON.stringify(data, null, 2);
}

/**
 * Reorder object keys so that long text fields (like `content`, `prompt`)
 * come last. This makes YAML output more readable when content spans
 * multiple lines.
 */
export function reorderKeys(obj: unknown): unknown {
  if (Array.isArray(obj)) return obj.map(reorderKeys);
  if (obj !== null && typeof obj === 'object') {
    const rec = obj as Record<string, unknown>;
    const firstKeys = ['kind'];
    const lastKeys = ['link', 'content', 'prompt'];
    const ordered: Record<string, unknown> = {};
    for (const key of firstKeys) {
      if (key in rec) ordered[key] = rec[key];
    }
    for (const key of Object.keys(rec)) {
      if (!firstKeys.includes(key) && !lastKeys.includes(key)) ordered[key] = reorderKeys(rec[key]);
    }
    for (const key of lastKeys) {
      if (key in rec) ordered[key] = rec[key];
    }
    return ordered;
  }
  return obj;
}

export function formatYaml(data: unknown): string {
  const reordered = reorderKeys(data);
  return yaml.dump(reordered, { lineWidth: 120, noRefs: true }).trimEnd();
}

/**
 * Format multiple resources as Kubernetes-style multi-document YAML.
 * Each item gets its own `---` separated document with a `kind` field.
 */
export function formatYamlMultiDoc(items: Array<{ kind: string } & Record<string, unknown>>): string {
  return items
    .map((item) => {
      const reordered = reorderKeys(item);
      return '---\n' + yaml.dump(reordered, { lineWidth: 120, noRefs: true }).trimEnd();
    })
    .join('\n');
}
