const SPORT_VISUAL_CONTEXT: Record<string, string> = {
  nfl: 'helmet clash at the line, packed football stadium',
  nba: 'explosive drive to the rim, bright arena lights',
  mlb: 'violent swing in the batter box, dramatic ballpark lights',
  nhl: 'hard stop on the ice, cold arena haze',
  soccer: 'strike on goal, roaring stadium crowd',
  mma: 'faceoff inside the cage, hard spotlight contrast',
  ncaab: 'fast break in a loud college arena',
  ncaaf: 'college football collision under stadium lights',
};

const FILLER_PATTERNS = [
  /\bno text\b/gi,
  /\bno logo(?:s)?\b/gi,
  /\bno watermark(?:s)?\b/gi,
  /\bwithout text\b/gi,
  /\bwithout logo(?:s)?\b/gi,
  /\bwithout watermark(?:s)?\b/gi,
  /\bwatermark(?:s)?\b/gi,
  /\blogo(?:s)?\b/gi,
];

const NEGATIVE_PROMPT = [
  'text',
  'logo',
  'watermark',
  'scoreboard overlay',
  'cartoon',
  'anime',
  'illustration',
  'cgi',
  '3d render',
  'plastic skin',
  'waxy skin',
  'deformed hands',
  'extra fingers',
  'extra limbs',
  'duplicate athlete',
  'blurry face',
  'low detail',
].join(', ');

function cleanPrompt(rawPrompt: string): string {
  let cleaned = rawPrompt
    .replace(/[`"']/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();

  for (const pattern of FILLER_PATTERNS) {
    cleaned = cleaned.replace(pattern, ' ');
  }

  return cleaned.replace(/\s+/g, ' ').trim();
}

function trimToWordLimit(value: string, limit: number): string {
  const words = value.split(/\s+/).filter(Boolean);
  if (words.length <= limit) {
    return words.join(' ');
  }
  return words.slice(0, limit).join(' ');
}

export function buildFluxSocialImagePrompt(rawPrompt: string, sport?: string): {
  prompt: string;
  negativePrompt: string;
} {
  const cleaned = cleanPrompt(rawPrompt);
  const subject = trimToWordLimit(cleaned, 24) || 'dramatic sports action';
  const visualContext = SPORT_VISUAL_CONTEXT[(sport || '').toLowerCase()] || 'dramatic stadium atmosphere';
  const prompt = trimToWordLimit(
    `${subject}, ${visualContext}, editorial sports photography, photorealistic, natural anatomy, dramatic lighting, shallow depth of field`,
    42,
  );

  return {
    prompt,
    negativePrompt: NEGATIVE_PROMPT,
  };
}
