/**
 * Platform Detector
 * Detects social media platform from URL
 */

import {
  Platform,
  PlatformDetectionResult,
  SUPPORTED_DOMAINS,
} from "@/types/download";

/**
 * Detects the social media platform from a URL
 * @param url - The URL to detect platform from
 * @returns PlatformDetectionResult with platform and confidence
 */
export function detectPlatform(url: string): PlatformDetectionResult {
  try {
    const urlObj = new URL(url);
    const hostname = urlObj.hostname.toLowerCase().replace("www.", "");

    // Check each platform's domains
    for (const [platform, domains] of Object.entries(SUPPORTED_DOMAINS) as [
      Platform,
      string[],
    ][]) {
      if (platform === "unknown") continue;

      for (const domain of domains) {
        if (hostname === domain || hostname.endsWith("." + domain)) {
          return {
            platform,
            confidence: "high",
            originalUrl: url,
            normalizedUrl: normalizeUrl(url, platform),
          };
        }
      }
    }

    // Check for known URL patterns even if domain doesn't match exactly
    const patternResult = detectByPattern(url);
    if (patternResult) {
      return patternResult;
    }

    return {
      platform: "unknown",
      confidence: "low",
      originalUrl: url,
    };
  } catch {
    return {
      platform: "unknown",
      confidence: "low",
      originalUrl: url,
    };
  }
}

/**
 * Detects platform by URL patterns
 */
function detectByPattern(url: string): PlatformDetectionResult | null {
  const patterns: { pattern: RegExp; platform: Platform }[] = [
    // YouTube patterns
    { pattern: /youtube\.com\/watch\?v=[\w-]+/i, platform: "youtube" },
    { pattern: /youtu\.be\/[\w-]+/i, platform: "youtube" },
    { pattern: /youtube\.com\/shorts\/[\w-]+/i, platform: "youtube" },
    { pattern: /youtube\.com\/embed\/[\w-]+/i, platform: "youtube" },

    // Instagram patterns
    { pattern: /instagram\.com\/(p|reel|tv)\/[\w-]+/i, platform: "instagram" },
    { pattern: /instagr\.am\/(p|reel|tv)\/[\w-]+/i, platform: "instagram" },

    // TikTok patterns
    { pattern: /tiktok\.com\/@[\w.]+\/video\/\d+/i, platform: "tiktok" },
    { pattern: /vm\.tiktok\.com\/[\w-]+/i, platform: "tiktok" },
    { pattern: /vt\.tiktok\.com\/[\w-]+/i, platform: "tiktok" },

    // Twitter/X patterns
    { pattern: /twitter\.com\/\w+\/status\/\d+/i, platform: "twitter" },
    { pattern: /x\.com\/\w+\/status\/\d+/i, platform: "twitter" },

    // Facebook patterns
    { pattern: /facebook\.com\/.*\/videos\/\d+/i, platform: "facebook" },
    { pattern: /facebook\.com\/watch\/?\?v=\d+/i, platform: "facebook" },
    { pattern: /fb\.watch\/[\w-]+/i, platform: "facebook" },
  ];

  for (const { pattern, platform } of patterns) {
    if (pattern.test(url)) {
      return {
        platform,
        confidence: "high",
        originalUrl: url,
      };
    }
  }

  return null;
}

/**
 * Normalizes URL for specific platforms
 * Some platforms need URL normalization for better API compatibility
 */
function normalizeUrl(url: string, platform: Platform): string {
  try {
    const urlObj = new URL(url);

    switch (platform) {
      case "youtube": {
        // Convert youtu.be to youtube.com
        if (urlObj.hostname === "youtu.be") {
          const videoId = urlObj.pathname.slice(1);
          return `https://www.youtube.com/watch?v=${videoId}`;
        }
        // Convert shorts to regular watch URL
        if (urlObj.pathname.startsWith("/shorts/")) {
          const videoId = urlObj.pathname.replace("/shorts/", "");
          return `https://www.youtube.com/watch?v=${videoId}`;
        }
        return url;
      }

      case "tiktok": {
        // Keep the original URL - Cobalt handles short URLs
        return url;
      }

      case "twitter": {
        // Ensure x.com URLs are handled properly
        return url;
      }

      default:
        return url;
    }
  } catch {
    return url;
  }
}

/**
 * Checks if a platform is supported
 */
export function isPlatformSupported(platform: Platform): boolean {
  return platform !== "unknown";
}

/**
 * Gets the best URL to use for downloading
 * Some platforms work better with normalized URLs
 */
export function getBestUrlForDownload(url: string): string {
  const result = detectPlatform(url);
  return result.normalizedUrl || result.originalUrl;
}
