/**
 * Unified marketplace sync — one call refreshes everything from every
 * configured source (public + each enterprise tenant):
 *   - registry.json + wizard templates per source (lib/connectors/sync)
 *   - installed connector manifests (so on-disk yaml updates)
 *   - workflows: pipelines + recipes per source (lib/workflow-marketplace)
 *   - skills: public only for now; enterprise skill sync is a separate task
 *
 * Errors per sub-step are isolated — a failing skills repo doesn't block
 * connector sync, etc. Returned summary spells out each leg so the UI
 * can show what actually landed.
 */

import { syncRegistry } from './connectors/sync';
import { syncMarketplace as syncWorkflows } from './workflow-marketplace';
import { syncSkills } from './skills';

export interface MarketplaceSyncResult {
  ok: boolean;
  connectors: { ok: boolean; sources_ok?: number; sources_total?: number; manifests_refreshed?: number; error?: string };
  workflows: { ok: boolean; recipes?: number; pipelines?: number; error?: string };
  skills: { ok: boolean; synced?: number; error?: string };
  fetched_at: string;
}

export async function syncAll(): Promise<MarketplaceSyncResult> {
  const fetched_at = new Date().toISOString();

  // 1. Connectors — registry + wizard templates per source + installed manifests
  let connectors: MarketplaceSyncResult['connectors'];
  try {
    const r = await syncRegistry({ refreshInstalled: true });
    connectors = {
      ok: !!r.ok,
      sources_ok: (r.sources || []).filter(s => s.ok).length,
      sources_total: (r.sources || []).length,
      manifests_refreshed: r.manifests_refreshed || 0,
      error: r.error,
    };
  } catch (e) {
    connectors = { ok: false, error: (e as Error).message };
  }

  // 2. Workflows — pipelines + recipes per source
  let workflows: MarketplaceSyncResult['workflows'];
  try {
    const r = await syncWorkflows();
    workflows = { ok: !!r.ok, recipes: r.recipes, pipelines: r.pipelines, error: r.error };
  } catch (e) {
    workflows = { ok: false, error: (e as Error).message };
  }

  // 3. Skills — public only for now (enterprise skill sources are a
  // separate phase in the marketplace roadmap).
  let skills: MarketplaceSyncResult['skills'];
  try {
    const r = await syncSkills();
    skills = { ok: !r.error, synced: r.synced, error: r.error };
  } catch (e) {
    skills = { ok: false, error: (e as Error).message };
  }

  return {
    ok: connectors.ok && workflows.ok && skills.ok,
    connectors,
    workflows,
    skills,
    fetched_at,
  };
}
