import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { descriptions } from "../constants/descriptions.js";
import { steps } from "../constants/steps.js";
import { z } from "zod";

type SupportedIntegrationPlatform = "android" | "ios";

const booleanFlagSchema = (description: string) =>
  z
    .preprocess((value) => {
      if (typeof value === "boolean") return value;
      if (typeof value === "string") {
        const normalized = value.trim().toLowerCase();
        if (normalized === "true") return true;
        if (normalized === "false") return false;
      }
      if (typeof value === "number") {
        if (value === 1) return true;
        if (value === 0) return false;
      }
      return value;
    }, z.boolean().optional())
    .describe(description);

function isAndroidAppId(appId: string): boolean {
  return /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)+$/.test(appId.trim());
}

function isIosAppId(appId: string): boolean {
  const trimmed = appId.trim();
  return /^\d+$/.test(trimmed) || /^id\d+$/.test(trimmed);
}

// The iOS steps target the AppsFlyer 6.x API. In 7.x `appsFlyerDevKey` and
// `appleAppID` became read-only and `waitForATTUserAuthorization` was
// deprecated, so the generated Swift does not compile against it. Keep this at
// 6 until the iOS steps are migrated.
const IOS_SDK_MAJOR = 6;
const IOS_SDK_FALLBACK_VERSION = "6.18.1";

function parseSemver(version: string): number[] | null {
  const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
  return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
}

async function resolveLatestIosSdkVersion(major: number): Promise<string> {
  const res = await fetch(
    "https://trunk.cocoapods.org/api/v1/pods/AppsFlyerFramework"
  );
  if (!res.ok) {
    throw new Error(`CocoaPods API returned ${res.status}`);
  }

  const data = (await res.json()) as { versions?: { name?: string }[] };

  // CocoaPods returns the versions unsorted, and a string sort ranks "6.9.2"
  // above "6.18.1", so compare each component numerically.
  const latest = (data.versions ?? [])
    .map((entry) => parseSemver(String(entry?.name ?? "")))
    .filter((parts): parts is number[] => parts !== null && parts[0] === major)
    .sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2])
    .pop();

  if (!latest) {
    throw new Error(`no ${major}.x versions found`);
  }

  return latest.join(".");
}

function normalizePlatform(value?: unknown): SupportedIntegrationPlatform | null {
  if (typeof value !== "string") return null;
  const normalized = value.trim().toLowerCase();
  if (normalized === "android") return "android";
  if (normalized === "ios") return "ios";
  return null;
}

function resolvePlatform(argsPlatform: unknown): SupportedIntegrationPlatform | null {
  const fromArgs = normalizePlatform(argsPlatform);
  if (fromArgs) return fromArgs;

  const appId = process.env.APP_ID?.trim();
  if (!appId) return null;
  if (isAndroidAppId(appId)) return "android";
  if (isIosAppId(appId)) return "ios";
  return null;
}

export function integrateSdk(server: McpServer): void {
  server.registerTool(
    "integrateSdk",
    {
      title: "Integrate AppsFlyer SDK",
      description: descriptions.integrateSdk,
      inputSchema: {
        platform: z
          .enum(["android", "ios"])
          .optional()
          .describe(
            "Target platform for integration. If omitted, the tool infers it from APP_ID."
          ),
        useResponseListener: z
          .boolean()
          .optional()
          .describe(
            "Android only: whether to use a response listener when starting the SDK"
          ),
        isDelegate: booleanFlagSchema(
          'iOS only: answer to "Do you want to support Scene Delegate?"'
        ),
        isResponseListener: booleanFlagSchema(
          "iOS only: whether to use a response listener when starting the SDK"
        ),
        isATT: booleanFlagSchema("iOS only: whether to include ATT setup steps"),
        isCUID: booleanFlagSchema(
          "iOS only: whether to include customerUserID setup steps"
        ),
      },
    },
    async (args) => {
      const {
        platform,
        useResponseListener,
        isDelegate,
        isResponseListener,
        isATT,
        isCUID,
      } = args;

      const resolvedPlatform = resolvePlatform(platform);
      if (!resolvedPlatform) {
        return {
          content: [
            {
              type: "text",
              text:
                "❌ Could not determine platform. Provide `platform` as `android` or `ios`, or set APP_ID to a valid Android package name or iOS Apple App ID.",
            },
          ],
        };
      }

      const devKey = process.env.DEV_KEY;
      if (!devKey) {
        return {
          content: [
            {
              type: "text",
              text: `❌ DevKey environment variable (DEV_KEY) not set.`,
            },
          ],
        };
      }

      if (resolvedPlatform === "android") {
        if (useResponseListener === undefined) {
          return {
            content: [
              {
                type: "text",
                text: "❌ 'useResponseListener' parameter is required for Android integration.",
              },
            ],
          };
        }

        let latestVersion = null;
        try {
          const res = await fetch(
            "https://repo1.maven.org/maven2/com/appsflyer/af-android-sdk/maven-metadata.xml"
          );
          const metadata = await res.text();
          const releaseMatch = metadata.match(/<release>([^<]+)<\/release>/);
          const latestMatch = metadata.match(/<latest>([^<]+)<\/latest>/);
          latestVersion = releaseMatch?.[1] || latestMatch?.[1] || null;
        } catch (err: any) {
          return {
            content: [
              {
                type: "text",
                text: `❌ Failed to fetch latest SDK version: ${err.message}`,
              },
            ],
          };
        }

        if (!latestVersion) {
          return {
            content: [
              {
                type: "text",
                text: "❌ Could not extract latest SDK version from response.",
              },
            ],
          };
        }

        const rawSteps = useResponseListener
          ? steps.integrateSdk.withResponseListener
          : steps.integrateSdk.regular;

        const stepsWithReplacements = rawSteps.map((step) => {
          let updated = step.replace(/<YOUR-DEV-KEY>/g, devKey);
          if (updated.includes(`implementation 'com.appsflyer:af-android-sdk'`)) {
            updated = updated.replace(
              `implementation 'com.appsflyer:af-android-sdk'`,
              `implementation 'com.appsflyer:af-android-sdk:${latestVersion}'`
            );
          }
          return updated;
        });

        const executionPrefix =
          "Prefer applying the following integration steps directly in the user's Android project files whenever possible, instead of leaving copy/paste-only guidance.";

        return {
          content: [
            {
              type: "text",
              text: `${executionPrefix}\n\n${stepsWithReplacements.join("\n\n")}`,
            },
          ],
        };
      }

      const missingIosFlags: string[] = [];
      if (isDelegate === undefined) missingIosFlags.push("isDelegate");
      if (isResponseListener === undefined) missingIosFlags.push("isResponseListener");
      if (isATT === undefined) missingIosFlags.push("isATT");
      if (isCUID === undefined) missingIosFlags.push("isCUID");

      if (missingIosFlags.length > 0) {
        const usedAndroidFlag = useResponseListener !== undefined;
        return {
          content: [
            {
              type: "text",
              text:
                `❌ Missing required iOS integration parameters: ${missingIosFlags.join(", ")}.\n` +
                `For iOS, always ask the user and pass explicit true/false values for: isResponseListener, isDelegate, isATT, and isCUID. Do not assume omitted flags are true or false.` +
                (usedAndroidFlag
                  ? `\nNote: 'useResponseListener' is Android-only and is ignored for iOS.`
                  : ""),
            },
          ],
        };
      }

      const appId = process.env.APP_ID;
      if (!appId) {
        return {
          content: [
            {
              type: "text",
              text: "❌ App ID environment variable (APP_ID) not set.",
            },
          ],
        };
      }

      let iosSdkVersion: string;
      try {
        iosSdkVersion = await resolveLatestIosSdkVersion(IOS_SDK_MAJOR);
      } catch {
        // Fall back to the last known-good pin. Emitting an unpinned Podfile
        // line would resolve to an incompatible major, so a stale-but-working
        // version is better than failing the whole integration.
        iosSdkVersion = IOS_SDK_FALLBACK_VERSION;
      }

      const rawSteps = steps.integrateAppsFlyerIosSdk({
        isDelegate,
        isResponseListener,
        isATT,
        isCUID,
        sdkVersion: iosSdkVersion,
      });

      const stepsWithReplacements = rawSteps.map((step) => {
        let updated = step.replace(/<YOUR-DEV-KEY>/g, devKey);
        updated = updated.replace(/<APPLE_APP_ID>/g, appId);
        return updated;
      });

      return {
        content: [
          {
            type: "text",
            text: stepsWithReplacements.join("\n\n"),
          },
        ],
      };
    }
  );
}
