import { businessModuleHints } from "@/data/onboarding";
import { developmentModules } from "@/data/commercial";
import { getPlanAppFormatId, getPlanDefaultModules } from "@/lib/planDisplay";
import type { Plan } from "@/types/plan";

export interface ProjectInsights {
  estimatedScreens: number;
  complexityLabel: "Baixa" | "Média" | "Alta" | "Enterprise";
  complexityScore: number;
  suggestedModuleIds: string[];
  appFormatId: string;
}

const BASE_SCREENS = 12;

export function inferAppFormatFromPlatforms(platforms: string[]): string {
  const hasPwa = platforms.includes("pwa");
  const hasAndroid = platforms.includes("android");
  const hasIos = platforms.includes("ios");

  if (hasPwa && hasAndroid && hasIos) return "full";
  if (hasAndroid && hasIos) return "android-ios";
  if (hasIos) return "ios";
  if (hasAndroid) return "android";
  if (hasPwa) return "pwa";
  return "android-ios";
}

export function getSuggestedModules(
  businessType: string,
  planSlug: string,
  catalogPlan?: Plan,
): string[] {
  const hints = businessModuleHints[businessType] ?? [];
  const fromPlan = getPlanDefaultModules(catalogPlan);
  return [...new Set([...fromPlan, ...hints])].filter((id) =>
    developmentModules.some((m) => m.id === id),
  );
}

export function calculateProjectInsights(
  businessType: string,
  planSlug: string,
  moduleIds: string[],
  optionalIds: string[],
  platforms: string[],
  needsAdmin: boolean,
  needsWebsite: boolean,
  needsHelpdesk: boolean,
  catalogPlan?: Plan,
): ProjectInsights {
  const appFormatId = getPlanAppFormatId(catalogPlan, platforms);

  let score = 0;
  score += moduleIds.length * 8;
  score += optionalIds.length * 6;
  if (platforms.includes("ios")) score += 12;
  if (platforms.includes("android")) score += 8;
  if (platforms.includes("pwa")) score += 4;
  if (needsAdmin) score += 10;
  if (needsWebsite) score += 8;
  if (needsHelpdesk) score += 6;
  if (planSlug === "enterprise") score += 25;
  else if (planSlug === "business") score += 12;

  const estimatedScreens =
    BASE_SCREENS +
    moduleIds.length * 4 +
    optionalIds.length * 3 +
    (needsAdmin ? 8 : 0) +
    (needsWebsite ? 4 : 0) +
    (needsHelpdesk ? 3 : 0);

  let complexityLabel: ProjectInsights["complexityLabel"] = "Baixa";
  if (score >= 70) complexityLabel = "Enterprise";
  else if (score >= 45) complexityLabel = "Alta";
  else if (score >= 25) complexityLabel = "Média";

  return {
    estimatedScreens,
    complexityLabel,
    complexityScore: score,
    suggestedModuleIds: getSuggestedModules(businessType, planSlug, catalogPlan),
    appFormatId,
  };
}
