import roleRecordsLite from "@/data/role-records-lite.json";
import { industryTaxonomy, resolveIndustrySelection } from "@/lib/business-roles-taxonomy";
import type { OnboardingInput, RoleGroups, RoleIntelligence } from "@/lib/types";

const roleRecords = roleRecordsLite as Record<
  string,
  {
    id: string;
    industry: string;
    category: string;
    roleGroups: RoleGroups;
    firstHire: string;
    nextHire: string;
    revenueDrivers: string[];
    growthBottlenecks: string[];
    brandLxftUseCases: string[];
  }
>;

function getIndustryRecord(industryId: string) {
  return roleRecords[industryId];
}

export const ROLE_GROUP_LABELS: Record<keyof RoleGroups, string> = {
  leadership: "Leadership",
  revenue: "Revenue",
  growth: "Growth",
  operations: "Operations",
  production: "Production / Delivery",
  compliance: "Compliance",
  technology: "Technology",
};

/** Demo-specific team context — shows realistic gaps per industry */
const DEMO_TEAM_CONTEXT: Record<
  string,
  { currentTeam: string[]; priorityHire?: string; opportunityRoleLink?: string }
> = {
  "demo-apex-roofing": {
    currentTeam: ["Owner", "Roofing Crew Lead", "Estimator", "Office Admin"],
    priorityHire: "Marketing Manager",
    opportunityRoleLink:
      "Storm-response opportunities need a Marketing Manager to launch geo ads and a Reputation Manager to capture reviews within 48 hours.",
  },
  "demo-glow-studio": {
    currentTeam: ["Owner/Injector", "Front Desk", "Medical Assistant"],
    priorityHire: "Patient Coordinator",
    opportunityRoleLink:
      "Reactivation campaigns need a Patient Coordinator to run SMS sequences and a Marketing Manager to fill membership tiers.",
  },
  "demo-stackline": {
    currentTeam: ["Founder/CEO", "Founding Engineer", "Part-time SDR"],
    priorityHire: "Onboarding Concierge",
    opportunityRoleLink:
      "Active buyer on LinkedIn needs an SDR + Onboarding Concierge to close — your data shows 34% close rate with concierge vs 12% without.",
  },
  "demo-farm-table": {
    currentTeam: ["Owner/Chef", "Line Cooks", "Part-time Server"],
    priorityHire: "Catering Sales Coordinator",
    opportunityRoleLink:
      "Unanswered catering inquiries need a Catering Sales Coordinator to respond within 1 hour and an Event Manager for corporate accounts.",
  },
  "demo-momentum-fitness": {
    currentTeam: ["Owner/Head Coach", "2 Trainers", "Front Desk"],
    priorityHire: "Membership Retention Specialist",
    opportunityRoleLink:
      "Corporate wellness RFP needs a Sales Coordinator to submit proposals and a Retention Specialist to prevent the March cancellation cliff.",
  },
  "demo-greenedge-landscaping": {
    currentTeam: ["Owner", "Crew Lead", "Estimator"],
    priorityHire: "Marketing Manager",
    opportunityRoleLink:
      "HOA RFP and spring package launch need a Marketing Manager for proposals and a Reputation Manager to close the review gap vs competitors.",
  },
  "demo-vitalmed-supply": {
    currentTeam: ["Owner", "Account Manager", "Warehouse Lead"],
    priorityHire: "Business Development Rep",
    opportunityRoleLink:
      "Surgery center RFP requires a BDR to pursue procurement contacts and a Compliance Lead for FDA documentation in the response.",
  },
  "demo-clearsmile-dental": {
    currentTeam: ["Owner/Dentist", "Hygienist", "Front Desk"],
    priorityHire: "Treatment Coordinator",
    opportunityRoleLink:
      "Hot Invisalign lead needs Front Desk to call within 30 min — hire a Treatment Coordinator to own cosmetic case conversion.",
  },
  "demo-comfortzone-hvac": {
    currentTeam: ["Owner", "Lead Technician", "Dispatcher"],
    priorityHire: "ComfortClub Sales Specialist",
    opportunityRoleLink:
      "Heat wave emergency calls need Dispatcher capacity — train techs as ComfortClub specialists to hit 400 maintenance subscribers.",
  },
  "demo-luxe-realty": {
    currentTeam: ["Lead Agent/Owner", "Buyer's Agent", "Transaction Coordinator"],
    priorityHire: "Investor Relations Specialist",
    opportunityRoleLink:
      "Duplex investor buyer needs an Investor Relations Specialist for ROI packages and a Marketing Manager to reduce Zillow dependency.",
  },
};

function getDemoTeamContext(demoId?: string) {
  if (!demoId) return undefined;
  if (DEMO_TEAM_CONTEXT[demoId]) return DEMO_TEAM_CONTEXT[demoId];
  if (demoId.startsWith("demo-")) {
    return DEMO_TEAM_CONTEXT[demoId];
  }
  return DEMO_TEAM_CONTEXT[`demo-${demoId}`];
}

export function isRoleIntelligenceComplete(roles?: RoleIntelligence): boolean {
  if (!roles) return false;
  if (roles.industryId === "unknown") return false;
  const roleCount = Object.values(roles.roleGroups).flat().length;
  return roleCount >= 10;
}

function resolveIndustryRecord(input: OnboardingInput) {
  const subtype = input.businessSubtype ?? input.industry;
  const match = resolveIndustrySelection(input.industryCategory, subtype);

  if (match) {
    const record = getIndustryRecord(match.industryId);
    if (record) return record;
  }

  if (input.businessSubtype) {
    const retry = resolveIndustrySelection(input.industryCategory, input.businessSubtype);
    if (retry) {
      const record = getIndustryRecord(retry.industryId);
      if (record) return record;
    }
  }

  // Last resort: match business subtype label across all categories
  if (input.businessSubtype) {
    for (const category of industryTaxonomy.taxonomy) {
      const found = category.businessTypes.find((b) => b.label === input.businessSubtype);
      if (found) {
        const record = getIndustryRecord(found.industryId);
        if (record) return record;
      }
    }
  }

  return undefined;
}

function inferMissingRoles(groups: RoleGroups, currentTeam: string[], challenge: string): string[] {
  const current = new Set(currentTeam.map((r) => r.toLowerCase()));
  const challengeLower = challenge.toLowerCase();

  const priorityGroups: (keyof RoleGroups)[] =
    challengeLower.includes("lead") || challengeLower.includes("customer") || challengeLower.includes("book")
      ? ["growth", "revenue", "operations"]
      : challengeLower.includes("retention") || challengeLower.includes("churn") || challengeLower.includes("cancel")
        ? ["operations", "growth", "revenue"]
        : challengeLower.includes("competitor") || challengeLower.includes("review") || challengeLower.includes("brand")
          ? ["growth", "revenue"]
          : ["growth", "revenue", "operations"];

  const missing: string[] = [];
  for (const group of priorityGroups) {
    for (const role of groups[group]) {
      const roleLower = role.toLowerCase();
      const covered = [...current].some(
        (c) => roleLower.includes(c) || c.includes(roleLower.split("/")[0]?.trim() ?? ""),
      );
      if (!covered) missing.push(role);
    }
  }

  return [...new Set(missing)].slice(0, 4);
}

function buildHowUsed(
  record: NonNullable<ReturnType<typeof getIndustryRecord>>,
  missingRoles: string[],
  priorityHire: string,
  topPriority?: string,
): string[] {
  return [
    `BrandLxft mapped ${record.industry} to ${Object.values(record.roleGroups).flat().length} key roles across 7 functions.`,
    `Your #1 hiring gap: ${priorityHire} — aligned with "${record.nextHire}" for businesses at your stage.`,
    missingRoles.length
      ? `Missing roles blocking growth: ${missingRoles.slice(0, 3).join(", ")}.`
      : "Core role coverage looks solid — focus on execution bandwidth next.",
    topPriority
      ? `Today's priority "${topPriority}" maps to ${priorityHire} ownership.`
      : record.brandLxftUseCases[0] ?? "Detect missing roles and recommend next hire.",
  ];
}

export interface BuildRoleOptions {
  demoId?: string;
  topPriority?: string;
  currentTeam?: string[];
}

export function buildRoleIntelligence(
  input: OnboardingInput,
  options: BuildRoleOptions = {},
): RoleIntelligence | undefined {
  const record = resolveIndustryRecord(input);
  if (!record) return undefined;

  const demoCtx = getDemoTeamContext(options.demoId);
  const currentTeam =
    demoCtx?.currentTeam ??
    options.currentTeam ??
    ["Owner", record.firstHire.split(" or ")[0] ?? record.firstHire];

  const missingRoles = inferMissingRoles(record.roleGroups, currentTeam, input.biggestChallenge || "");
  const priorityHire =
    demoCtx?.priorityHire ?? missingRoles[0] ?? record.nextHire.split(" or ")[0] ?? record.nextHire;

  return {
    industryId: record.id,
    industry: record.industry,
    industryCategory: input.industryCategory,
    businessSubtype: input.businessSubtype,
    roleGroups: record.roleGroups,
    firstHire: record.firstHire,
    nextHire: record.nextHire,
    revenueDrivers: record.revenueDrivers,
    growthBottlenecks: record.growthBottlenecks,
    currentTeam,
    missingRoles,
    priorityHire,
    howBrandLxftUsesRoles: buildHowUsed(record, missingRoles, priorityHire, options.topPriority),
    opportunityRoleLink:
      demoCtx?.opportunityRoleLink ??
      (options.topPriority
        ? `${priorityHire} should own execution on "${options.topPriority}".`
        : undefined),
  };
}

export function enrichBusinessWithRoles<T extends { input: OnboardingInput; metrics?: { topPriorityToday?: string }; id?: string; roleIntelligence?: RoleIntelligence }>(
  business: T,
): T & { roleIntelligence: RoleIntelligence } {
  if (business.roleIntelligence && isRoleIntelligenceComplete(business.roleIntelligence)) {
    return business as T & { roleIntelligence: RoleIntelligence };
  }

  const demoId =
    business.id?.startsWith("demo-") ? business.id : business.id ? `demo-${business.id}` : undefined;

  const built =
    buildRoleIntelligence(business.input, {
      demoId,
      topPriority: business.metrics?.topPriorityToday,
    }) ?? buildRoleIntelligence(business.input);

  return {
    ...business,
    roleIntelligence: built ?? {
      industryId: "unknown",
      industry: business.input.industry,
      industryCategory: business.input.industryCategory,
      businessSubtype: business.input.businessSubtype,
      roleGroups: {
        leadership: ["Owner"],
        revenue: ["Sales Lead"],
        growth: ["Marketing Manager"],
        operations: ["Operations Manager"],
        production: ["Delivery Lead"],
        compliance: [],
        technology: [],
      },
      firstHire: "Operations support",
      nextHire: "Marketing Manager",
      revenueDrivers: ["Owner-led sales"],
      growthBottlenecks: ["No dedicated growth owner"],
      currentTeam: ["Owner"],
      missingRoles: ["Marketing Manager"],
      priorityHire: "Marketing Manager",
      howBrandLxftUsesRoles: ["Assign a growth owner to execute today's priorities."],
    },
  };
}
