/**
 * Environment-based social platform enable/disable + credential readiness.
 *
 * Backward compatible:
 * - Existing META_*, FACEBOOK_*, LINKEDIN_*, GOOGLE_* vars still work.
 * - If FACEBOOK_ENABLED (etc.) is unset, platforms that already ship as "active"
 *   stay enabled when OAuth app credentials are present.
 * - Tokens for publishing remain per-project OAuth tokens in Connected Accounts -
 *   static FACEBOOK_ACCESS_TOKEN / LINKEDIN_ACCESS_TOKEN env values are NOT used
 *   for multi-project publishing (documented as unsupported for this architecture).
 */

import {
  getLinkedInConfig,
  getMetaConfig,
  getYouTubeConfig,
} from "@/lib/env";
import {
  SOCIAL_PLATFORM_REGISTRY,
  type RegistryContentType,
  type RegistryDestination,
  type SocialPlatformId,
} from "@/lib/social/config/platform-registry";

export type SocialIntegrationStatus =
  | "enabled"
  | "disabled"
  | "missing_credentials"
  | "not_implemented"
  | "coming_soon";

/** @deprecated Prefer RegistryDestination from platform-registry */
export type SocialDestinationSupport = RegistryDestination | "none";

export interface PlatformIntegrationReport {
  platform: SocialPlatformId;
  label: string;
  implemented: boolean;
  envEnabled: boolean;
  credentialsConfigured: boolean;
  status: SocialIntegrationStatus;
  /** ready | disabled | missing_credentials | not_implemented | coming_soon */
  readiness: string;
  supportsOAuth: boolean;
  supportsPublish: boolean;
  connectionRequired: boolean;
  destinations: RegistryDestination[];
  supportedDestinations: RegistryDestination[];
  contentTypes: RegistryContentType[];
  supportedContentTypes: RegistryContentType[];
  notes: string[];
  requiredEnv: string[];
  missingEnv: string[];
}

function parseBool(raw: string | undefined, defaultValue: boolean): boolean {
  if (raw === undefined || raw.trim() === "") return defaultValue;
  const v = raw.trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(v)) return true;
  if (["0", "false", "no", "off"].includes(v)) return false;
  return defaultValue;
}

function hasValue(...keys: string[]): boolean {
  return keys.some((k) => Boolean(process.env[k]?.trim()));
}

/** Global kill-switch. Default true so existing deployments keep working. */
export function isSocialMediaGloballyEnabled(): boolean {
  return parseBool(process.env.SOCIAL_MEDIA_ENABLED, true);
}

function platformEnvEnabled(
  platform: SocialPlatformId,
  defaultWhenUnset: boolean,
): boolean {
  if (!isSocialMediaGloballyEnabled()) return false;
  const key = `${platform.toUpperCase()}_ENABLED`;
  if (platform === "twitter") {
    if (process.env.TWITTER_ENABLED !== undefined) {
      return parseBool(process.env.TWITTER_ENABLED, defaultWhenUnset);
    }
    if (process.env.X_ENABLED !== undefined) {
      return parseBool(process.env.X_ENABLED, defaultWhenUnset);
    }
  }
  return parseBool(process.env[key], defaultWhenUnset);
}

export function getMetaAppCredentials(): { appId: string; appSecret: string } {
  const cfg = getMetaConfig();
  return { appId: cfg.appId, appSecret: cfg.appSecret };
}

export function getLinkedInAppCredentials(): {
  clientId: string;
  clientSecret: string;
} {
  const cfg = getLinkedInConfig();
  return { clientId: cfg.clientId, clientSecret: cfg.clientSecret };
}

export function getYouTubeAppCredentials(): {
  clientId: string;
  clientSecret: string;
} {
  const cfg = getYouTubeConfig();
  return { clientId: cfg.clientId, clientSecret: cfg.clientSecret };
}

function missingKeys(keys: string[]): string[] {
  return keys.filter((k) => !process.env[k]?.trim());
}

function metaCredentialsOk(): { ok: boolean; missing: string[] } {
  const hasId = hasValue("META_APP_ID", "FACEBOOK_APP_ID", "FACEBOOK_CLIENT_ID");
  const hasSecret = hasValue(
    "META_APP_SECRET",
    "FACEBOOK_APP_SECRET",
    "FACEBOOK_CLIENT_SECRET",
  );
  const missing: string[] = [];
  if (!hasId) missing.push("META_APP_ID|FACEBOOK_APP_ID|FACEBOOK_CLIENT_ID");
  if (!hasSecret) {
    missing.push("META_APP_SECRET|FACEBOOK_APP_SECRET|FACEBOOK_CLIENT_SECRET");
  }
  return { ok: hasId && hasSecret, missing };
}

function linkedInCredentialsOk(): { ok: boolean; missing: string[] } {
  const keys = ["LINKEDIN_CLIENT_ID", "LINKEDIN_CLIENT_SECRET"];
  return { ok: keys.every((k) => hasValue(k)), missing: missingKeys(keys) };
}

function youTubeCredentialsOk(): { ok: boolean; missing: string[] } {
  const hasId = hasValue("GOOGLE_CLIENT_ID", "YOUTUBE_CLIENT_ID");
  const hasSecret = hasValue("GOOGLE_CLIENT_SECRET", "YOUTUBE_CLIENT_SECRET");
  const missing: string[] = [];
  if (!hasId) missing.push("GOOGLE_CLIENT_ID|YOUTUBE_CLIENT_ID");
  if (!hasSecret) missing.push("GOOGLE_CLIENT_SECRET|YOUTUBE_CLIENT_SECRET");
  return { ok: hasId && hasSecret, missing };
}

export function getLinkedInDestinationHints(): {
  personIdConfigured: boolean;
  organizationIdConfigured: boolean;
  note: string;
} {
  const personIdConfigured = hasValue("LINKEDIN_PERSON_ID");
  const organizationIdConfigured = hasValue("LINKEDIN_ORGANIZATION_ID");
  return {
    personIdConfigured,
    organizationIdConfigured,
    note:
      SOCIAL_PLATFORM_REGISTRY.linkedin.notes?.join(" ") ??
      "Publishing uses the LinkedIn member connected via OAuth.",
  };
}

export function getFacebookDestinationCapabilities(): {
  pagePosting: boolean;
  personalProfilePosting: boolean;
  note: string;
} {
  return {
    pagePosting: SOCIAL_PLATFORM_REGISTRY.facebook.destinations.includes("page"),
    personalProfilePosting: false,
    note:
      SOCIAL_PLATFORM_REGISTRY.facebook.notes?.join(" ") ??
      "Facebook Page posting only.",
  };
}

function threadsCredentialsOk(): { ok: boolean; missing: string[] } {
  const hasId = hasValue(
    "THREADS_APP_ID",
    "META_APP_ID",
    "FACEBOOK_APP_ID",
    "FACEBOOK_CLIENT_ID",
  );
  const hasSecret = hasValue(
    "THREADS_APP_SECRET",
    "META_APP_SECRET",
    "FACEBOOK_APP_SECRET",
    "FACEBOOK_CLIENT_SECRET",
  );
  const missing: string[] = [];
  if (!hasId) missing.push("THREADS_APP_ID|META_APP_ID|FACEBOOK_APP_ID");
  if (!hasSecret) missing.push("THREADS_APP_SECRET|META_APP_SECRET|FACEBOOK_APP_SECRET");
  return { ok: hasId && hasSecret, missing };
}

function pinterestCredentialsOk(): { ok: boolean; missing: string[] } {
  const hasId = hasValue("PINTEREST_APP_ID", "PINTEREST_CLIENT_ID");
  const hasSecret = hasValue("PINTEREST_APP_SECRET", "PINTEREST_CLIENT_SECRET");
  const missing: string[] = [];
  if (!hasId) missing.push("PINTEREST_APP_ID|PINTEREST_CLIENT_ID");
  if (!hasSecret) missing.push("PINTEREST_APP_SECRET|PINTEREST_CLIENT_SECRET");
  return { ok: hasId && hasSecret, missing };
}

function tiktokCredentialsOk(): { ok: boolean; missing: string[] } {
  const hasId = hasValue("TIKTOK_CLIENT_KEY", "TIKTOK_CLIENT_ID");
  const hasSecret = hasValue("TIKTOK_CLIENT_SECRET");
  const missing: string[] = [];
  if (!hasId) missing.push("TIKTOK_CLIENT_KEY|TIKTOK_CLIENT_ID");
  if (!hasSecret) missing.push("TIKTOK_CLIENT_SECRET");
  return { ok: hasId && hasSecret, missing };
}

function credentialsFor(platform: SocialPlatformId): { ok: boolean; missing: string[] } {
  switch (platform) {
    case "facebook":
    case "instagram":
      return metaCredentialsOk();
    case "linkedin":
      return linkedInCredentialsOk();
    case "youtube":
      return youTubeCredentialsOk();
    case "twitter":
      return {
        ok: hasValue("TWITTER_CLIENT_ID") && hasValue("TWITTER_CLIENT_SECRET"),
        missing: missingKeys(["TWITTER_CLIENT_ID", "TWITTER_CLIENT_SECRET"]),
      };
    case "threads":
      return threadsCredentialsOk();
    case "pinterest":
      return pinterestCredentialsOk();
    case "tiktok":
      return tiktokCredentialsOk();
  }
}

function mapDestinationsForReport(
  platform: SocialPlatformId,
): RegistryDestination[] {
  return [...SOCIAL_PLATFORM_REGISTRY[platform].destinations];
}

export function getPlatformIntegrationReport(
  platform: SocialPlatformId,
): PlatformIntegrationReport {
  const cap = SOCIAL_PLATFORM_REGISTRY[platform];
  const envEnabled = platformEnvEnabled(platform, cap.defaultEnabled);
  const creds = credentialsFor(platform);
  const notes: string[] = [...(cap.notes ?? [])];

  let status: SocialIntegrationStatus;
  let supportsOAuth = false;
  let supportsPublish = false;

  if (!cap.implemented) {
    status = cap.comingSoon ? "coming_soon" : "not_implemented";
  } else if (!envEnabled) {
    status = "disabled";
    notes.push(
      `Set ${platform.toUpperCase()}_ENABLED=true and configure OAuth app credentials.`,
    );
  } else if (!creds.ok) {
    status = "missing_credentials";
    notes.push("OAuth app credentials missing — Connect and publish are blocked.");
  } else {
    status = "enabled";
    supportsOAuth = cap.oauthRequired;
    supportsPublish = true;
  }

  const destinations = status === "enabled" ? mapDestinationsForReport(platform) : [];
  const readiness = status === "enabled" ? "ready" : status;

  return {
    platform,
    label: cap.label,
    implemented: cap.implemented,
    envEnabled,
    credentialsConfigured: creds.ok,
    status,
    readiness,
    supportsOAuth,
    supportsPublish: supportsPublish && status === "enabled",
    connectionRequired: cap.oauthRequired && cap.implemented,
    destinations,
    supportedDestinations: mapDestinationsForReport(platform),
    contentTypes: [...cap.contentTypes],
    supportedContentTypes: [...cap.contentTypes],
    notes,
    requiredEnv: cap.requiredEnv,
    missingEnv: creds.missing,
  };
}

export function listPlatformIntegrationReports(): PlatformIntegrationReport[] {
  return (Object.keys(SOCIAL_PLATFORM_REGISTRY) as SocialPlatformId[]).map(
    getPlatformIntegrationReport,
  );
}

export function isPlatformIntegrationActive(platform: string): boolean {
  const id = platform as SocialPlatformId;
  if (!(id in SOCIAL_PLATFORM_REGISTRY)) return false;
  return getPlatformIntegrationReport(id).status === "enabled";
}

export function isPlatformPublishEnabled(platform: string): boolean {
  const id = platform as SocialPlatformId;
  if (!(id in SOCIAL_PLATFORM_REGISTRY)) return false;
  return getPlatformIntegrationReport(id).supportsPublish;
}

export function getPlatformBlockReason(platform: string): {
  code: string;
  message: string;
  action: string;
} | null {
  const id = platform as SocialPlatformId;
  if (!(id in SOCIAL_PLATFORM_REGISTRY)) {
    return {
      code: "UNKNOWN_PLATFORM",
      message: `Unknown platform: ${platform}`,
      action: "Choose a supported platform",
    };
  }
  const report = getPlatformIntegrationReport(id);
  if (report.status === "enabled") return null;
  if (report.status === "disabled") {
    return {
      code: "PLATFORM_DISABLED",
      message: `${report.label} integration is disabled.`,
      action: `Set ${id.toUpperCase()}_ENABLED=true (and SOCIAL_MEDIA_ENABLED=true)`,
    };
  }
  if (report.status === "missing_credentials") {
    return {
      code: "MISSING_CREDENTIALS",
      message: `${report.label} OAuth app credentials are incomplete.`,
      action: `Configure: ${report.missingEnv.join(", ")}`,
    };
  }
  if (report.status === "coming_soon") {
    return {
      code: "COMING_SOON",
      message: `${report.label} is not available in this release.`,
      action: "Enable an implemented platform or wait for this integration",
    };
  }
  return {
    code: "NOT_IMPLEMENTED",
    message: `${report.label} API integration is not implemented.`,
    action: `Leave ${id.toUpperCase()}_ENABLED=false until a provider is shipped`,
  };
}
