import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { wrapUntrustedContent } from "./contentGuard.js";

type GuardResult = {
  ok: boolean;
  message?: string;
};

const VALIDATION_DEVICE_ID = "0";

type GuardPlatform = "android" | "ios" | "unknown";

// stores the final validation result per platform
const oneTimeResultByPlatform: Partial<Record<GuardPlatform, GuardResult>> = {};
// stores the validation result for the current platform
const inFlightByPlatform: Partial<Record<GuardPlatform, Promise<GuardResult>>> = {};

function missingCredentialsResult(devKey?: string, appId?: string): GuardResult {
  const missing: string[] = [];
  if (!devKey) missing.push("DEV_KEY");
  if (!appId) missing.push("APP_ID");

  return {
    ok: false,
    message:
      `❌ Missing required value(s): ${missing.join(", ")}.\n` +
      `Please add APP_ID and DEV_KEY in mcp.json (env).\n` +
      `Only the user who configured this MCP server can fix this.\n` +
      `Until these are provided and validated, tools are blocked.`,
  };
}

function checkAndroidBundle(appID: string): boolean {
  return (
    /^([A-Za-z]{1}[A-Za-z\d_]*\.)+[A-Za-z][A-Za-z\d_]*$/.test(appID) ||
    /^([A-Za-z]{1}[A-Za-z\d_]*\.)+[A-Za-z][A-Za-z\d_]*-[A-Za-z][A-Za-z\d_]*$/.test(
      appID
    )
  );
}

function checkAppleAppID(appID: string): boolean {
  // check if app id contains numbers only or starts with id
  if (/^\d+$/.test(appID)) {
    return true;
  } else if (appID.indexOf("id") === 0) {
    if (/^\d+$/.test(appID.replace("id", ""))) {
      return true;
    }
  }
  return false;
}

function parseJsonSafe(raw: string): any {
  try {
    return JSON.parse(raw);
  } catch {
    return raw;
  }
}

async function validateAgainstAppsFlyer(
  appId: string,
  devKey: string
): Promise<GuardResult> {
  if (!appId || !devKey) {
    return {
      ok: false,
      message:
        `❌ Missing parameters for AppsFlyer check.\n` +
        `APP_ID: ${appId ? "provided" : "missing"}\n` +
        `DEV_KEY: ${devKey ? "provided" : "missing"}\n` +
        `The user who configured this MCP server must update APP_ID/DEV_KEY in mcp.json.`,
    };
  }

  const encodedAppId = encodeURIComponent(appId);
  const encodedDevKey = encodeURIComponent(devKey);
  const encodedDeviceId = encodeURIComponent(VALIDATION_DEVICE_ID);
  const url =
    `https://gcdsdk.appsflyer.com/install_data/v4.0/${encodedAppId}` +
    `?devkey=${encodedDevKey}&device_id=${encodedDeviceId}`;

  try {
    const response = await fetch(url, {
      method: "GET",
      headers: { accept: "application/json" },
    });

    const rawBody = await response.text();
    const parsedBody = parseJsonSafe(rawBody);

    if (response.status === 200) {
      return { ok: true };
    }

    // device_id="0" yields 404 "Attribution data … not available" when creds are valid.
    // Only accept that specific response — any other 404 fails closed.
    if (response.status === 404) {
      if (
        typeof parsedBody === "object" &&
        parsedBody !== null &&
        typeof parsedBody.error_reason === "string" &&
        parsedBody.error_reason.toLowerCase().includes("attribution data") &&
        parsedBody.error_reason.toLowerCase().includes("not available")
      ) {
        return { ok: true };
      }
      return {
        ok: false,
        message:
          `❌ Tool blocked: AppsFlyer credential precheck returned an unexpected 404.\n` +
          `The user who configured this MCP server must update APP_ID/DEV_KEY in mcp.json.`,
      };
    }

    if (response.status === 400 || response.status === 403) {
      const reason =
        typeof parsedBody === "object" && parsedBody?.error_reason
          ? parsedBody.error_reason
          : `HTTP ${response.status}`;
      return {
        ok: false,
        message:
          `❌ Tool blocked: AppsFlyer credential precheck failed.\n` +
          `error_reason: ${reason}\n` +
          `The user who configured this MCP server must update APP_ID/DEV_KEY in mcp.json.`,
      };
    }

    const compactBody = String(
      typeof parsedBody === "string" ? parsedBody : JSON.stringify(parsedBody)
    )
      .replace(/\s+/g, " ")
      .slice(0, 300);
    return {
      ok: false,
      message:
        `❌ Tool blocked: AppsFlyer credential precheck failed.\n` +
        `Reason: APP_ID + DEV_KEY did not pass validation with AppsFlyer.\n` +
        `HTTP ${response.status} ${response.statusText}\n` +
        `${compactBody ? `Response: ${wrapUntrustedContent(compactBody, "api-error")}\n` : ""}` +
        `The user who configured this MCP server must update APP_ID/DEV_KEY in mcp.json.`,
    };
  } catch (error: any) {
    return {
      ok: false,
      message:
        `❌ Tool blocked: could not run AppsFlyer credential precheck.\n` +
        `Error: ${error?.message || error}\n` +
        `The user who configured this MCP server must verify network access and update APP_ID/DEV_KEY in mcp.json if needed.`,
    };
  }
}

function normalizeGuardPlatform(platform?: string): GuardPlatform {
  if (platform === "android") return "android";
  if (platform === "ios") return "ios";
  return "unknown";
}

export async function assertAppsFlyerCredentials(
  platform?: string
): Promise<GuardResult> {
  const platformKey = normalizeGuardPlatform(platform);

  if (oneTimeResultByPlatform[platformKey]) {
    return oneTimeResultByPlatform[platformKey] as GuardResult;
  }

  if (inFlightByPlatform[platformKey]) {
    return inFlightByPlatform[platformKey] as Promise<GuardResult>;
  }

  inFlightByPlatform[platformKey] = (async () => {
    const devKey = process.env.DEV_KEY?.trim();
    const appId = process.env.APP_ID?.trim();

    if (!devKey || !appId) {
      const result = missingCredentialsResult(devKey, appId);
      oneTimeResultByPlatform[platformKey] = result;
      return result;
    }

    if (platformKey === "android" && !checkAndroidBundle(appId)) {
      const result: GuardResult = {
        ok: false,
        message:
          `❌ APP_ID is not a valid Android application ID format.\n` +
          `The user who configured this MCP server must update APP_ID in mcp.json to a valid Android application ID (for example: com.example.app).`,
      };
      oneTimeResultByPlatform[platformKey] = result;
      return result;
    }

    if (platformKey === "ios" && !checkAppleAppID(appId)) {
      const result: GuardResult = {
        ok: false,
        message:
          `❌ APP_ID is not a valid iOS Apple App ID format.\n` +
          `Please provide a numeric APP_ID (for example: 1512793879 or id1512793879) in mcp.json.`,
      };
      oneTimeResultByPlatform[platformKey] = result;
      return result;
    }

    if (
      platformKey === "unknown" &&
      !checkAndroidBundle(appId) &&
      !checkAppleAppID(appId)
    ) {
      const result: GuardResult = {
        ok: false,
        message:
          `❌ APP_ID is not a valid Android or iOS app ID format.\n` +
          `Use Android format (for example: com.example.app) or iOS format (numeric, with optional "id" prefix) in mcp.json.`,
      };
      oneTimeResultByPlatform[platformKey] = result;
      return result;
    }

    const result = await validateAgainstAppsFlyer(appId, devKey);
    oneTimeResultByPlatform[platformKey] = result;
    return result;
  })();

  try {
    return await (inFlightByPlatform[platformKey] as Promise<GuardResult>);
  } finally {
    inFlightByPlatform[platformKey] = undefined;
  }
}

export function installAppsFlyerCredentialGuard(server: McpServer): void {
  const originalRegisterTool = server.registerTool.bind(server) as any;

  (server as any).registerTool = (name: string, config: any, handler: any) => {
    const wrappedHandler = async (args: any, extra: any) => {
      const validation = await assertAppsFlyerCredentials(args?.platform);
      if (!validation.ok) {
        return {
          isError: true,
          content: [
            {
              type: "text",
              text:
                (validation.message ?? "❌ AppsFlyer credential validation failed.") +
                `\nStop: the user who configured this MCP server must update APP_ID/DEV_KEY in mcp.json, then restart the server before calling AppsFlyer tools again.`,
            },
          ],
        };
      }

      return handler(args, extra);
    };

    return originalRegisterTool(name, config, wrappedHandler);
  };
}
