/**
 * Central capability registry for social platforms.
 * UI, status API, publish gates, country availability, and media validation
 * should prefer this over ad-hoc lists.
 */

export type SocialPlatformId =
  | "linkedin"
  | "facebook"
  | "instagram"
  | "twitter"
  | "threads"
  | "pinterest"
  | "youtube"
  | "tiktok";

export type RegistryDestination =
  | "page"
  | "profile"
  | "organization"
  | "channel"
  | "instagram_business"
  | "board";

export type RegistryContentType = "text" | "image" | "caption" | "video";

/** Media / caption limits used by pre-publish validation. */
export interface PlatformMediaRules {
  maxCaptionLength: number;
  image?: {
    minWidth?: number;
    minHeight?: number;
    maxBytes?: number;
    mimeTypes: string[];
    aspectRatios?: string[];
  };
  video?: {
    maxDurationSeconds?: number;
    minDurationSeconds?: number;
    maxBytes?: number;
    mimeTypes: string[];
    required: boolean;
  };
  /** At least one of these must be present to publish. */
  requiresAnyOf: Array<"caption" | "image" | "video">;
}

export interface PlatformCapability {
  id: SocialPlatformId;
  label: string;
  /** Publish + OAuth code exists in this release. */
  implemented: boolean;
  /** Default when `{PLATFORM}_ENABLED` is unset. */
  defaultEnabled: boolean;
  /** @deprecated Prefer implemented=false + status not_implemented */
  comingSoon?: boolean;
  oauthRequired: boolean;
  destinations: RegistryDestination[];
  contentTypes: RegistryContentType[];
  requiredEnv: string[];
  mediaRules: PlatformMediaRules;
  /**
   * ISO 3166-1 alpha-2 country codes where the platform is available.
   * `"*"` means all countries (subject to blockedCountries).
   */
  supportedCountries: string[] | "*";
  /**
   * Countries where the platform must not be offered (e.g. regulatory bans).
   * Overridable via PLATFORM_BLOCKED_COUNTRIES_{ID} env.
   */
  blockedCountries: string[];
  notes?: string[];
}

const IMAGE_COMMON = ["image/jpeg", "image/png", "image/webp"];
const VIDEO_MP4 = ["video/mp4"];

export const SOCIAL_PLATFORM_REGISTRY: Record<SocialPlatformId, PlatformCapability> = {
  facebook: {
    id: "facebook",
    label: "Facebook",
    implemented: true,
    defaultEnabled: true,
    oauthRequired: true,
    destinations: ["page"],
    contentTypes: ["text", "image"],
    requiredEnv: [
      "META_APP_ID|FACEBOOK_APP_ID|FACEBOOK_CLIENT_ID",
      "META_APP_SECRET|FACEBOOK_APP_SECRET|FACEBOOK_CLIENT_SECRET",
    ],
    mediaRules: {
      maxCaptionLength: 63206,
      image: { mimeTypes: IMAGE_COMMON, maxBytes: 10 * 1024 * 1024 },
      requiresAnyOf: ["caption", "image"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: [
      "Posts to a Facebook Page selected during OAuth.",
      "Personal profile posting is not supported by Meta Page APIs.",
    ],
  },
  instagram: {
    id: "instagram",
    label: "Instagram",
    implemented: true,
    defaultEnabled: true,
    oauthRequired: true,
    destinations: ["instagram_business"],
    contentTypes: ["image", "caption"],
    requiredEnv: [
      "META_APP_ID|FACEBOOK_APP_ID|FACEBOOK_CLIENT_ID",
      "META_APP_SECRET|FACEBOOK_APP_SECRET|FACEBOOK_CLIENT_SECRET",
    ],
    mediaRules: {
      maxCaptionLength: 2200,
      image: {
        mimeTypes: IMAGE_COMMON,
        minWidth: 320,
        maxBytes: 8 * 1024 * 1024,
      },
      requiresAnyOf: ["image"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: [
      "Requires Instagram Business/Creator linked to a Facebook Page.",
      "Image + caption only in this release.",
    ],
  },
  linkedin: {
    id: "linkedin",
    label: "LinkedIn",
    implemented: true,
    defaultEnabled: true,
    oauthRequired: true,
    destinations: ["profile"],
    contentTypes: ["text", "image"],
    requiredEnv: ["LINKEDIN_CLIENT_ID", "LINKEDIN_CLIENT_SECRET"],
    mediaRules: {
      maxCaptionLength: 3000,
      image: { mimeTypes: IMAGE_COMMON, maxBytes: 10 * 1024 * 1024 },
      requiresAnyOf: ["caption", "image"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: [
      "Publishes as the OAuth-connected member (profile).",
      "Company Page (organization) posting is not implemented yet.",
    ],
  },
  youtube: {
    id: "youtube",
    label: "YouTube",
    implemented: true,
    defaultEnabled: true,
    oauthRequired: true,
    destinations: ["channel"],
    contentTypes: ["video"],
    requiredEnv: [
      "GOOGLE_CLIENT_ID|YOUTUBE_CLIENT_ID",
      "GOOGLE_CLIENT_SECRET|YOUTUBE_CLIENT_SECRET",
    ],
    mediaRules: {
      maxCaptionLength: 5000,
      video: {
        required: true,
        mimeTypes: VIDEO_MP4,
        maxDurationSeconds: 43200,
        maxBytes: 256 * 1024 * 1024,
      },
      requiresAnyOf: ["video"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: ["Requires VIDEO_PROVIDER=ffmpeg and a generated MP4 on the post."],
  },
  twitter: {
    id: "twitter",
    label: "X (Twitter)",
    implemented: false,
    defaultEnabled: false,
    oauthRequired: false,
    destinations: [],
    contentTypes: [],
    requiredEnv: ["TWITTER_CLIENT_ID", "TWITTER_CLIENT_SECRET"],
    mediaRules: {
      maxCaptionLength: 280,
      requiresAnyOf: ["caption"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: ["Not implemented. Enable flag alone does not activate publishing."],
  },
  threads: {
    id: "threads",
    label: "Threads",
    implemented: true,
    defaultEnabled: false,
    oauthRequired: true,
    destinations: ["profile"],
    contentTypes: ["text", "image", "caption"],
    requiredEnv: [
      "THREADS_APP_ID|META_APP_ID|FACEBOOK_APP_ID|FACEBOOK_CLIENT_ID",
      "THREADS_APP_SECRET|META_APP_SECRET|FACEBOOK_APP_SECRET|FACEBOOK_CLIENT_SECRET",
    ],
    mediaRules: {
      maxCaptionLength: 500,
      image: { mimeTypes: IMAGE_COMMON, maxBytes: 8 * 1024 * 1024 },
      requiresAnyOf: ["caption", "image"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: [
      "Uses Threads Graph API (threads.net OAuth).",
      "Requires a Meta app with the Threads product enabled.",
    ],
  },
  pinterest: {
    id: "pinterest",
    label: "Pinterest",
    implemented: true,
    defaultEnabled: false,
    oauthRequired: true,
    destinations: ["board"],
    contentTypes: ["image", "caption"],
    requiredEnv: ["PINTEREST_APP_ID|PINTEREST_CLIENT_ID", "PINTEREST_APP_SECRET|PINTEREST_CLIENT_SECRET"],
    mediaRules: {
      maxCaptionLength: 500,
      image: {
        mimeTypes: IMAGE_COMMON,
        minWidth: 200,
        minHeight: 300,
        maxBytes: 20 * 1024 * 1024,
      },
      requiresAnyOf: ["image"],
    },
    supportedCountries: "*",
    blockedCountries: [],
    notes: [
      "Creates a Pin on the default (or selected) board.",
      "Image is required — text-only Pins are not supported.",
    ],
  },
  tiktok: {
    id: "tiktok",
    label: "TikTok",
    implemented: true,
    defaultEnabled: false,
    oauthRequired: true,
    destinations: ["profile"],
    contentTypes: ["video", "caption"],
    requiredEnv: ["TIKTOK_CLIENT_KEY|TIKTOK_CLIENT_ID", "TIKTOK_CLIENT_SECRET"],
    mediaRules: {
      maxCaptionLength: 2200,
      video: {
        required: true,
        mimeTypes: VIDEO_MP4,
        minDurationSeconds: 3,
        maxDurationSeconds: 600,
        maxBytes: 287 * 1024 * 1024,
      },
      requiresAnyOf: ["video"],
    },
    // Consumer TikTok access is restricted in several markets; overridable via env.
    supportedCountries: "*",
    blockedCountries: ["IN"],
    notes: [
      "Requires TikTok Content Posting API credentials and a generated MP4.",
      "Blocked by default in countries where TikTok consumer access is restricted (e.g. IN) — override with PLATFORM_BLOCKED_COUNTRIES_TIKTOK.",
    ],
  },
};

export const SOCIAL_PLATFORM_IDS = Object.keys(
  SOCIAL_PLATFORM_REGISTRY,
) as SocialPlatformId[];

export function getPlatformCapability(
  platform: string,
): PlatformCapability | undefined {
  return SOCIAL_PLATFORM_REGISTRY[platform as SocialPlatformId];
}

export function listImplementedPlatforms(): PlatformCapability[] {
  return SOCIAL_PLATFORM_IDS.map((id) => SOCIAL_PLATFORM_REGISTRY[id]).filter(
    (p) => p.implemented,
  );
}

export function platformSupportsDestination(
  platform: string,
  destination: RegistryDestination,
): boolean {
  const cap = getPlatformCapability(platform);
  return Boolean(cap?.destinations.includes(destination));
}

export function platformSupportsContentType(
  platform: string,
  contentType: RegistryContentType,
): boolean {
  const cap = getPlatformCapability(platform);
  return Boolean(cap?.contentTypes.includes(contentType));
}

/** Content types the post is attempting to publish (heuristic from payload). */
export function inferContentTypes(input: {
  caption?: string;
  imageUrl?: string | null;
  videoUrl?: string | null;
}): RegistryContentType[] {
  const types: RegistryContentType[] = [];
  if (input.caption?.trim()) {
    types.push("text");
    types.push("caption");
  }
  if (input.imageUrl) types.push("image");
  if (input.videoUrl) types.push("video");
  return types;
}
