import type { Business, UserWorkplaceRole } from "@/lib/types";

export const AI_LEADER_ROLE_NAME = "BrandLxft AI Leader";

const OWNER_PATTERNS = [/owner/i, /ceo/i, /founder/i, /president/i, /managing partner/i, /general manager/i];

export function inferUserRoleTitle(business: Business): string {
  const team = business.roleIntelligence?.currentTeam ?? [];
  const match = team.find((member) => OWNER_PATTERNS.some((p) => p.test(member)));
  if (match) return match.includes("/") ? match : match.replace(/^Owner$/i, "Owner / CEO");
  return "Owner / CEO";
}

export function resolveUserRole(business: Business): UserWorkplaceRole {
  if (business.userRole) return business.userRole;
  return {
    title: inferUserRoleTitle(business),
    aiLeaderEnabled: false,
  };
}

export function enrichUserRole(business: Business): Business {
  if (business.userRole) return business;
  return {
    ...business,
    userRole: resolveUserRole(business),
  };
}

export function getAiLeaderBrief(business: Business): string {
  const user = resolveUserRole(business);
  const top = business.metrics.topPriorityToday;
  const revenue = business.metrics.revenuePotential;
  const priorityHire = business.roleIntelligence?.priorityHire;

  if (!user.aiLeaderEnabled) {
    return `You're operating as ${user.title}. Turn on AI Leader in Settings when you want BrandLxft to drive priorities like a boss.`;
  }

  return [
    `${user.title}, here's your focus: ${top}.`,
    `Revenue in play: $${revenue.toLocaleString()}.`,
    priorityHire
      ? `I'm assigning ${priorityHire} agents to support execution — run Role Agents or let me orchestrate below.`
      : `Run your Role Agents today — I'll hold you accountable to what moves revenue.`,
  ].join(" ");
}

export function getLeadershipDelegateRole(business: Business): string {
  return business.roleIntelligence?.priorityHire ?? business.roleIntelligence?.nextHire ?? "Marketing Manager";
}
