/**
 * AI Prompt Library for Image Generation Prompt Enhancement
 *
 * Takes user form inputs + brand context and produces a highly detailed,
 * optimized image-generation prompt for DALL-E 3 / ChatGPT Image Generation.
 *
 * Key design goals:
 * - Produce professional, production-ready results even with minimal user input
 * - Deeply leverage all available brand context (strategy, visual identity, business profile)
 * - Fill in missing details intelligently from brand data
 * - Ensure output matches brand identity, audience, tone, colors, and style
 * - Generate premium-quality, visually sophisticated, and creative results
 * - Avoid common AI art pitfalls (flat, generic, simple, stock-photo aesthetics)
 */

// ============================================
// TYPES
// ============================================

export interface ImageEnhancementInputs {
  // User form inputs
  description: string;
  objective?: string;
  style: string;
  targetAudience?: string;
  platform: string;
  aspectRatio: string;
  additionalInstructions?: string;

  // Brand context (fetched server-side)
  brandName?: string;
  brandColors?: string[];
  brandTone?: string;
  brandPersonality?: string[];
  brandArchetype?: string;
  businessDescription?: string;
  businessIndustry?: string;
  icpDescription?: string;

  // Brand asset context (from enhanced Add Asset form)
  assetTypeCategory?: string;   // e.g. 'visual-identity', 'social-media-assets'
  assetCategory?: string;       // e.g. 'logo', 'favicon', 'social-og'
  assetRequirements?: string;   // user's requirements/description from the form

  // Brand Strategy context (from module-data/brand-strategy)
  brandStrategy?: {
    mission?: string;
    vision?: string;
    values?: string[] | string;
    positioning?: string;
    differentiators?: string[] | string;
    personalityTraits?: string[] | string;
    voiceTone?: string;
  };

  // Visual Identity context (from module-data/visual-identity)
  visualIdentity?: {
    colorPalette?: any;
    typography?: any;
    designPrinciples?: string[] | string;
    moodDescription?: string;
    visualStyle?: string;
  };

  // Brand Guidelines context (from module-data/brand-guidelines)
  brandGuidelines?: {
    dosAndDonts?: any;
    voiceGuidelines?: any;
    designRules?: any;
  };

  // Brand Manual context (from module-data/brand-manual)
  brandManual?: {
    summary?: string;
    usageStandards?: any;
  };

  // Founder context (from Founder profiles)
  founderNames?: string[];
  founderBios?: string[];
  founderResponsibilityAreas?: string[];

  // Brand SOP 1.7 — extended visual direction and guardrails
  brandVisualDirection?: string;
  brandVisualTheme?: string;
  brandConsistencyGuardrails?: {
    cannotChange?: string[];
    canEvolve?: string[];
    misuseExamples?: string[];
  };
  brandForbiddenDesignPatterns?: string[];

  // User instructions for re-enhancement
  userInstructions?: string;
}

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// STYLE GUIDANCE MAP
// ============================================

export const STYLE_GUIDANCE: Record<string, string> = {
  Realistic: 'photorealistic rendering with exceptional lifelike detail, natural lighting with dramatic depth, realistic textures and materials, DSLR-quality photography with cinematic composition',
  Illustration: 'professional illustration with refined line work and sophisticated artistic interpretation, polished hand-drawn quality with depth and dimension, detailed shading and texture',
  '3D': 'premium 3D rendered image with volumetric lighting, realistic materials and depth, cinematic composition with dramatic shadows and highlights, studio-quality rendering',
  Cartoon: 'polished cartoon style with bold outlines, vibrant yet harmonious colours, playful and expressive features with professional shading and depth',
  Minimalist: 'refined minimalist design with intentional white space, elegant simplicity with sophisticated composition, limited colour palette used with precision and purpose',
  Abstract: 'sophisticated abstract art with bold shapes, rich colour harmonies, expressive brushstrokes and layered textures, professional gallery-quality composition',
  Photography: 'professional photography with shallow depth of field, natural composition, studio-quality lighting with dramatic highlights and shadows, editorial-quality image',
  Watercolor: 'refined watercolour painting with soft colour bleeds and delicate washes, artistic texture and transparency, professional illustration quality with depth',
  PixelArt: 'detailed pixel art with retro aesthetic, carefully crafted limited colour palette, professional sprite-quality design with clean edges and depth',
  Sketch: 'professional pencil sketch with cross-hatching, refined line art with shading and depth, hand-drawn feel with sophisticated composition',
  Noir: 'dramatic film noir style with high contrast black and white, moody atmosphere with deep shadows, cinematic lighting and composition',
  PopArt: 'bold pop art style with vibrant primary colours, halftone dots, comic-book inspired, Warhol-esque with professional polish and depth',
  Vintage: 'refined vintage aesthetic with faded colours, subtle grain texture, nostalgic warmth with professional composition and depth',
};

// ============================================
// PLATFORM GUIDANCE MAP
// ============================================

export const PLATFORM_GUIDANCE: Record<string, { usage: string; tips: string }> = {
  Instagram: { usage: 'social media post', tips: 'eye-catching, works in grid layout, bold focal point, square or portrait format, scroll-stopping composition' },
  Facebook: { usage: 'social media share', tips: 'clear at small thumbnail size, engaging and shareable, strong visual hierarchy' },
  LinkedIn: { usage: 'professional networking', tips: 'professional and polished, business-appropriate, trustworthy tone with depth and sophistication' },
  'Twitter/X': { usage: 'social media post', tips: 'works at small size, quick visual impact, bold and clear with professional polish' },
  Website: { usage: 'website hero or section image', tips: 'versatile for web layout, supports text overlay, clean composition with atmospheric depth' },
  Blog: { usage: 'blog featured image', tips: 'supports article title overlay, editorial feel with depth and atmosphere, relevant to content' },
  Email: { usage: 'email header or banner', tips: 'works in narrow horizontal format, clear at email width, professional with visual sophistication' },
  Presentation: { usage: 'slide visual', tips: 'works on large screen, not too busy, supports speaker points with clean visual hierarchy' },
  Print: {
    usage: 'print-ready professional material',
    tips: 'FLAT FACE-ON LAYOUT — must be shown completely flat and face-on as it would appear when printed, NOT as a 3D mockup, NOT at an angle, NOT with perspective, NOT floating with drop shadows. PRINT-READY with no additional edits required. Use CMYK-safe colours only (avoid neon/saturated RGB-only colours, screen glows, and pure RGB greens/blues that shift in CMYK conversion). Maintain safe margins: keep all critical content (text, logos, signatures) within the inner 85-90% of the frame to account for trim. Extend backgrounds and colour fills fully to the edge for bleed. Ensure all text is crisp and legible at print size. Use solid opaque fills rather than transparencies and screen-mode blending. Design must look like a finished print production file from a professional studio — clean, sharp, flat, directly printable.',
  },
  YouTube: { usage: 'video thumbnail', tips: 'works at small size, high contrast, clear subject, dramatic composition that demands attention' },
  TikTok: { usage: 'short-form video cover', tips: 'vertical format, attention-grabbing, works on mobile, bold visual impact' },
  Pinterest: { usage: 'pin image', tips: 'tall vertical format, visually appealing, stands out in grid feed with depth and richness' },
  Other: { usage: 'general purpose', tips: 'versatile and adaptable, clean composition with professional polish' },
};

// ============================================
// ASPECT RATIO → SIZE MAP
// ============================================

export const ASPECT_RATIO_SIZE_MAP: Record<string, string> = {
  '1:1': '1024x1024',
  '16:9': '1536x1024',
  '9:16': '1024x1536',
  '4:3': '1536x1024',
  '3:2': '1536x1024',
  '3:4': '1024x1536',
  '2:3': '1024x1536',
  '3:1': '1536x512',
};

export const COGVIEW_SIZE_MAP: Record<string, string> = {
  '1:1': '1024x1024',
  '16:9': '1440x720',
  '9:16': '720x1440',
  '4:3': '1152x864',
  '3:2': '1440x720',
  '3:4': '864x1152',
  '2:3': '720x1440',
  '3:1': '1440x480',
};

export const OPENAI_TO_COGVIEW_SIZE_MAP: Record<string, string> = {
  '1024x1024': '1024x1024',
  '1536x1024': '1440x720',
  '1024x1536': '720x1440',
  '1792x1024': '1440x720',
  '1024x1792': '720x1440',
  '1536x512': '1440x480',
};

// ============================================
// ASSET CATEGORY GUIDANCE
// ============================================

export const ASSET_CATEGORY_GUIDANCE: Record<string, string> = {
  'logo': 'This is a brand LOGO design. Create a sophisticated, memorable, and distinctive logo with a strong silhouette and refined details. It must be scalable from 16px favicon to billboard size, working flawlessly on both light and dark backgrounds. Use a maximum of 2-3 brand colours with intentional contrast. The design must convey the brand personality through form, shape, and visual weight — not through photographic elements or complex gradients. Include subtle depth through careful use of shadows, highlights, or dimensional layering where appropriate. Avoid flat, generic, or overly simple shapes. The result should look like it was crafted by a professional design studio, not a basic icon generator.',
  'secondary-logo': 'This is a SECONDARY LOGO variation for the brand. Design an alternate, simplified version of the primary brand logo that works in contexts where the primary logo is too heavy — such as social media avatars, small print, co-branding situations, or condensed layouts. The secondary logo must maintain instant brand recognition through consistent colour palette, typography, and symbolic elements while being more compact and adaptable than the primary logo. Use the brand\'s secondary colour as the dominant colour with the primary colour as accent. Must be scalable from 32px to billboard size. The design must feel like a natural companion to the primary logo — not a different brand, but a flexible alternative. Professional, production-ready design with depth and visual sophistication.',
  'wordmark': 'This is a BRAND WORDMARK — a text-only logo treatment featuring the brand name in its signature typography. Design a distinctive, memorable wordmark where the typography itself IS the brand identity. Custom letterforms, ligatures, or typographic treatments that make the brand name instantly recognizable. Use brand colours with sophistication — the wordmark must work on both light and dark backgrounds. Must be legible at small sizes (down to 24px) and impactful at large sizes. Professional type design quality — not just typed text, but considered typographic art. The wordmark should express the brand personality through letter weight, spacing, and subtle customisations. Production-ready, print-ready design.',
  'logo-icon': 'This is a LOGO ICON/MARK (no text). Design a sophisticated, instantly recognizable icon that represents the brand identity. Must be legible at 16x16 and striking at 1024x1024. Use bold, confident shapes with a limited colour palette (2-3 colours max). Add subtle dimensionality through careful use of gradients, shadows, or layered elements. The icon must work independently without any text and be memorable at first glance. Avoid flat, simple shapes — aim for geometric elegance with visual depth.',
  'favicon': 'This is a FAVICON design. Create a bold, instantly recognizable icon at 16x16 or 32x32 size. Use strong shapes with 2-3 brand colours maximum. The design must be crystal clear at tiny sizes — use high contrast and simple geometry. Add a subtle dimensional effect (soft shadow or emboss) so it doesn\'t look flat. Simplicity with sophistication is the goal.',
  'app-icon': 'This is an APP ICON design. Create a polished, premium app icon that stands out on any device home screen. Must work beautifully at all sizes from 29x29 to 1024x1024. Use brand colours prominently with rich gradients, subtle shadows, and dimensional depth. The icon should feel tactile and inviting — like a physical button you want to press. Include depth through soft inner shadows, edge highlights, or glass-like effects where appropriate.',
  'brandPattern': 'This is a SEAMLESS BRAND PATTERN. Design a richly textured, sophisticated pattern that tiles seamlessly in all directions. Use brand colours and visual motifs with depth through overlapping elements, transparency, and layered shapes. The pattern should have visual complexity and interest — not just simple repeating shapes. It must be subtle enough for backgrounds while maintaining brand recognition. Think wallpaper-quality design with professional refinement.',
  'backgroundImage': 'This is a BRANDED BACKGROUND IMAGE. Create an atmospheric, richly layered background with cinematic depth and visual interest. Use brand colours with sophisticated gradients, subtle textures, and compositional depth. Include foreground, midground, and background elements to create dimension. The design must support text/content overlay without competing — use selective focus and atmospheric effects. Avoid flat, solid-colour backgrounds — aim for depth, texture, and visual richness.',
  'watermark': 'This is a BRAND WATERMARK design. Create an elegant, semi-transparent overlay that identifies brand ownership with sophistication. Must work over various image types and colours without being distracting. Use brand shapes or initials at reduced opacity with subtle depth through shadows or embossing. The watermark should feel premium, not generic — like a luxury brand stamp.',
  'virtual-background': 'This is a VIRTUAL BACKGROUND for video calls (Zoom/Google Meet). Create a professional, branded virtual background image suitable for 16:9 video conferencing. The design must: (1) look professional on camera without being distracting, (2) feature the company logo subtly placed — typically in a bottom corner or top corner, not centred, (3) use brand colours as a soft gradient or subtle pattern — never flat solid colours that cause chroma-key or edge-detection issues, (4) avoid fine text that becomes illegible on camera, (5) have a clear "safe zone" in the centre where the speaker\'s head will appear, (6) use subtle depth with blurred or soft-focus background elements to maintain professionalism. Landscape orientation (16:9). The design should feel like a premium office environment or elegant branded setting — sophisticated, not cluttered.',
  'social-og': 'This is an OPEN GRAPH social sharing image (1200x630px). Design a visually striking, scroll-stopping image with professional depth and polish. Include strong visual hierarchy, brand colours used with sophistication, and a clear focal point with dramatic composition. Use atmospheric lighting, depth of field, and dimensional layering. The image must communicate the brand message at a glance in a crowded feed — it should look like a professional ad, not a template.',
  'social-twitter': 'This is a TWITTER/X card image. Design a visually compelling image that demands attention in a fast-scrolling timeline. Bold composition with strong focal point, rich colour usage, and professional depth. Must work at both full-size and thumbnail views. Use dramatic lighting and composition to stop scrolling. The result should look polished and authoritative.',
  'social-linkedin': 'This is a LINKEDIN professional image. Create a polished, business-appropriate image that conveys authority and credibility. Professional colour palette with brand identity, sophisticated composition with depth and visual hierarchy. The image should feel trustworthy and premium — like a high-end corporate communication, not a stock photo.',
  'social-instagram': 'This is an INSTAGRAM post image. Create a visually stunning, highly engaging image with professional composition and depth. Square format (1080x1080) with eye-catching colours, dramatic lighting, and refined visual storytelling. Must look beautiful in both feed and grid views. Include atmospheric depth, texture, and visual richness — aim for the quality of top-tier brand content.',
  'social-facebook': 'This is a FACEBOOK share image. Create an engaging, shareable image with professional polish and depth. Clear at thumbnail size with strong visual hierarchy, rich colours, and atmospheric composition. The image should communicate value instantly and invite clicks. Use brand colours with sophistication — not just flat fills.',
  'social-tiktok': 'This is a TIKTOK cover image. Create a bold, attention-grabbing vertical image (9:16) with high contrast and dramatic visual impact. Use brand colours with maximum contrast and energy. The design should stop endless scrolling with its visual sophistication and dynamism. Include depth, texture, and movement to create a premium feel.',
  'social-youtube': 'This is a YOUTUBE video thumbnail. Design a high-impact thumbnail with dramatic composition, high contrast, and clear visual hierarchy. Must work at small sizes in the sidebar with bold colours and clear subject. Use professional lighting effects, depth, and atmospheric quality. The thumbnail should look like a premium content piece, not a basic screenshot.',
  'web-banner': 'This is a WEBSITE HERO BANNER. Create a cinematic, visually stunning hero image with atmospheric depth and professional compositional hierarchy. Use brand colours with sophisticated gradients, lighting effects, and dimensional layering. Must support text overlay with clear breathing room. The banner should establish the brand atmosphere instantly — like a movie poster, not a flat colour block.',
  'email-header': 'This is an EMAIL HEADER banner. Create a polished, professional header with visual depth and brand sophistication. Horizontal format (600-700px) with brand colours used elegantly — not just flat blocks. Include subtle textures, gradients, or lighting effects for professional polish. Must render correctly across all email clients.',
  'email-footer': 'This is an EMAIL FOOTER design. Create a clean, professional footer with brand presence and visual sophistication. Compact but well-crafted, with brand colours at reduced opacity and subtle depth. Should feel premium and functional, not an afterthought.',
  'presentation': 'This is a PRESENTATION SLIDE TEMPLATE. Design a clean, sophisticated slide with professional visual hierarchy and brand integration. Must work on large screens with clear focal areas for content. Use brand colours with depth — subtle background textures, dimensional elements, or atmospheric gradients. The slide should enhance the presenter\'s message with visual sophistication.',
  'document': 'This is a DOCUMENT TEMPLATE design. Create a professional, branded template with refined typography integration and visual sophistication. Brand colours in header/footer areas with depth and elegance. Suitable for reports, proposals, and white papers — should establish credibility through visual quality.',
  'other': 'This is a general BRAND ASSET design. Create a professional, polished, visually sophisticated design that reinforces the brand identity. Use brand colours and visual identity guidelines with depth, texture, and professional composition. The result should look production-ready — like it was created by a professional design studio, not a basic AI illustration.',

  // ── FOUNDER ASSET CATEGORY GUIDANCE ──
  // Default prompt used by the Founder module's platform-wise profile image
  // generator. Super Admin can edit this (or add variants) from the prompt
  // configuration panel — the module always loads the saved version.
  'founder-profile-image': 'This is a SOCIAL MEDIA PROFILE PICTURE (avatar) for a company founder. Create a polished, professional head-and-shoulders portrait, centred and framed so it stays clear and recognisable when cropped to a small circle. Use flattering, soft studio lighting, a clean uncluttered background with gentle depth of field, natural skin tones and sharp focus on the eyes. Business-appropriate styling that matches the platform the avatar is for. Square 1:1 composition with comfortable headroom. No text, no logos, no watermarks, no borders, no collage — a single subject, front-facing, looking at the camera.',

  // ── HR ASSET CATEGORY GUIDANCE ──

  'id-card-front': 'This is an ID CARD FRONT design. Create a professional corporate ID card shown COMPLETELY FLAT and FACE-ON — as it appears when printed and laid on a table, NOT as a 3D mockup or tilted card. The design must include: photo placeholder area (top-left or top-center), employee name, job title, department, company logo, and company name. Use brand colours for accents and borders. The card must feel official and secure — include a colour strip with brand colour, and professional typography hierarchy. Standard ID card size (85.6 × 54 mm). Keep all text and photo within safe margins (5mm from edges). CMYK-safe colours only, solid opaque fills, no screen glows or RGB-only effects. The design must look like a finished print file — clean, sharp, flat, directly printable.',
  'id-card-back': 'This is an ID CARD BACK design. Create the reverse side of a corporate ID card shown COMPLETELY FLAT and FACE-ON — NOT as a 3D mockup, NOT tilted. The design must include: barcode or QR code placeholder area, emergency contact information section, "If found, please return to" section with company address, blood group field, and a magnetic strip area at the bottom. Use brand colours subtly — this side is more functional but must still feel cohesive with the front. Standard ID card size (85.6 × 54 mm). Keep all content within safe margins (5mm from edges). CMYK-safe colours, solid fills only, no transparency effects. The design must look like a finished print file — clean, sharp, flat, directly printable.',
  'lanyard-design': 'This is a LANYARD DESIGN. Create a branded lanyard design shown FLAT as a horizontal strip — as it appears when laid flat for printing. The design must work as a continuous strip (approximately 900mm × 20mm visual area) with brand colours prominently displayed and repeating logo, tagline, or geometric pattern. Include a clip/attachment area indication. CMYK-safe colours only (solid fabric-friendly colours, no screen glows). Bold, clean designs reproduce best on fabric. Print-ready, no digital-only effects.',
  'employee-badge': 'This is an EMPLOYEE BADGE design shown COMPLETELY FLAT and FACE-ON — NOT as a 3D mockup or tilted perspective. The design must include: clear photo area, name, title, department, and company logo. Use brand colours for the header strip and accent elements. Standard badge proportions (approximately 2:3). Keep all text and photo within safe margins. CMYK-safe colours, solid opaque fills, no screen effects. Print-ready — must look like a finished badge print file.',
  'visiting-card': 'This is a VISITING CARD / BUSINESS CARD design shown COMPLETELY FLAT and FACE-ON — as it appears when printed and laid flat on a surface. NOT as a 3D mockup, NOT at an angle, NOT tilted, NOT floating with drop shadows, NOT standing up on edge. The ENTIRE card face must be visible straight-on with zero perspective. Include areas for: name, title, phone, email, website, and company logo. Use brand colours elegantly — not overwhelming but clearly present. Standard business card size (3.5 × 2 inches / 89 × 51 mm). 3mm safe margin on all sides for critical content. Full bleed backgrounds to the edge. CMYK-safe colours only — no neon or electric RGB colours. Solid opaque fills, no transparency effects. The design must look like a finished print file from a professional studio — flat, sharp, clean, directly printable.',
  'attendance-sheet': 'This is an ATTENDANCE SHEET template design shown FLAT — as it appears when printed on paper. Create a professional, branded attendance tracking sheet with: company header/logo, month/year field, date columns, employee name rows, and signature/in-out time fields. Use brand colours in the header and for accent lines. A4 portrait layout with 10mm safe margins. CMYK-safe colours, primarily black text with brand colour accents in header. Clean grid lines, legible at print size. Print-ready.',
  'internal-memo': 'This is an INTERNAL MEMO template design shown FLAT — as it appears when printed on paper. Create a professional branded memo template with: company logo/header, "MEMORANDUM" title, To/From/Date/Subject fields, and a clean body area. Use brand colours in the header strip and for section dividers. A4 portrait with 15mm safe margins. CMYK-safe brand colours, solid fills only. Crisp, legible typography at print size. Print-ready for office printing.',

  'notepad': 'This is a NOTEPAD design shown FLAT — as it appears when printed and laid on a desk. Create a branded notepad page with: company logo in the header area, subtle brand watermark or pattern in the background, lined or blank area for notes, and footer with company contact info. A4 portrait (3:4) with brand colour header and subtle background. CMYK-safe colours. Print-ready.',
  'diary-planner': 'This is a DIARY/PLANNER cover design shown FLAT — as it appears when printed. Create a premium branded diary/planner cover with: elegant cover with company logo, brand colour accents, date/calendar sections. The design must feel sophisticated and premium. A4 portrait (3:4). CMYK-safe colours with subtle texture effects (embossing-style shadows are OK for indicating print finishes, but NO 3D perspective of the book). Print-ready.',
  'file-folder': 'This is a FILE FOLDER design shown FLAT — as it appears when printed, NOT as a 3D folder mockup. Create a branded file folder with: company logo on the tab and front panel, brand colour accent strip, and a label area. Professional and functional. A4 portrait (3:4). CMYK-safe colours, solid fills. Print-ready.',
  'document-folder': 'This is a DOCUMENT FOLDER design shown FLAT — as it appears when printed, NOT as a 3D folder mockup. Create a professional document folder with: company logo prominently on the front, brand colour panels, and a clean layout. Must look premium and official. A4 portrait (3:4). CMYK-safe colours, solid fills. Print-ready.',
  'pen-branding': 'This is a PEN BRANDING design. Create a branded pen design specification shown as a FLAT technical illustration — NOT a 3D pen mockup. Show the pen barrel design flat with company logo, brand colours, and tagline laid out for print production. Very wide format (16:9). CMYK-safe colours. Print-ready production specification.',
  'desk-name-plate': 'This is a DESK NAME PLATE design shown FLAT — as it appears when printed/manufactured, NOT as a 3D mockup standing on a desk. Create a professional desk name plate with: employee name area, title/department line, and company logo. Wide landscape format (16:9). CMYK-safe colours, solid fills. Print-ready.',

  'offer-letter': 'This is an OFFER LETTER template design shown FLAT — as it appears when printed on paper. Create a formal, professional offer letter header and layout with: company logo and header, "Offer of Employment" title, structured sections for candidate details, position, salary, start date, and terms. A4 portrait (3:4) with 15mm safe margins. CMYK-safe brand colours in header and accents. Solid opaque fills. Crisp legible typography. Print-ready.',
  'experience-certificate': 'This is an EXPERIENCE CERTIFICATE design shown COMPLETELY FLAT — as it appears when printed and laid flat, NOT as a 3D certificate mockup or rolled parchment. Create an elegant, formal certificate with: decorative border, company logo/seal area, "Certificate of Experience" title, employee details section, duration and role description, and signature/seal areas. Use brand colours in the border and header with gold or silver accent elements (use warm gold #C5A55A or cool silver #C0C0C0 — CMYK-safe metallics, NOT screen-only bright yellow/grey). Landscape orientation (4:3). 10mm safe margins. Solid opaque fills, no transparency effects. Print-ready.',
  'appreciation-certificate': 'This is an APPRECIATION CERTIFICATE design shown COMPLETELY FLAT — as it appears when printed, NOT as a 3D rolled certificate or mockup with perspective. Create a beautiful, celebratory certificate with: ornamental border, company logo, "Certificate of Appreciation" title, recipient name area, achievement description, date, and signature areas. Use brand colours with celebratory gold accents (warm gold #C5A55A, CMYK-safe). Landscape orientation (4:3). 10mm safe margins. Solid fills, no screen effects. Print-ready.',
  'training-certificate': 'This is a TRAINING CERTIFICATE design shown COMPLETELY FLAT — as it appears when printed. Create a professional certificate with: structured border, company logo, "Certificate of Training" title, trainee name, course name, completion date, and authorised signature area. Brand colours with gold accents (warm gold #C5A55A, CMYK-safe). Landscape orientation (4:3). 10mm safe margins. Solid fills. Print-ready.',
  'completion-certificate': 'This is a COMPLETION CERTIFICATE design shown COMPLETELY FLAT — as it appears when printed. Create a formal certificate with: elegant border, company seal/logo area, "Certificate of Completion" title, recipient name, program details, completion date, and authorising signatures. Brand colours with metallic gold/silver accents (CMYK-safe metallics). Landscape orientation (4:3). 10mm safe margins. Solid opaque fills. Print-ready.',
  'internship-certificate': 'This is an INTERNSHIP CERTIFICATE design shown COMPLETELY FLAT — as it appears when printed. Create a professional certificate with: clean border, company logo, "Internship Certificate" title, intern name, department, duration, project details, and supervisor signature area. Brand colours, balanced and professional. Landscape orientation (4:3). 10mm safe margins. Solid fills. Print-ready.',
  'relieving-letter': 'This is a RELIEVING LETTER template design shown FLAT — as it appears when printed on paper. Create a formal letter header and layout with: company header/logo, "Relieving Letter" title, structured sections for employee details, last working day, clearance confirmation, and formal sign-off. A4 portrait (3:4) with 15mm safe margins. CMYK-safe brand colours in header. Solid fills. Print-ready.',
  'appointment-letter': 'This is an APPOINTMENT LETTER template design shown FLAT — as it appears when printed on paper. Create a formal letter header and layout with: company header/logo, "Letter of Appointment" title, structured sections for candidate details, position, terms of employment, and acceptance area. A4 portrait (3:4) with 15mm safe margins. CMYK-safe brand colours. Solid fills. Print-ready.',

  'welcome-kit': 'This is a WELCOME KIT design shown FLAT — as it appears when printed, NOT as a 3D box mockup. Create a branded welcome kit folder/cover design with: company branding, a checklist of included items, and a warm welcome message. Square format (1:1). CMYK-safe colours with friendly, inviting tone. Solid fills. Print-ready.',
  'handbook': 'This is an EMPLOYEE HANDBOOK cover design shown FLAT — as it appears when printed, NOT as a 3D book mockup. Create a professional cover with: company logo, "Employee Handbook" title, edition/year, and subtle brand pattern or texture in the background. A4 portrait (3:4). CMYK-safe brand colours. Print-ready.',
  'code-of-conduct': 'This is a CODE OF CONDUCT document header design shown FLAT — as it appears when printed. Create a professional document header with: company logo, "Code of Conduct" title, and structured section indicators. A4 portrait (3:4) with 15mm margins. CMYK-safe colours. Print-ready.',
  'onboarding-checklist': 'This is an ONBOARDING CHECKLIST design shown FLAT — as it appears when printed. Create a branded checklist with: company header/logo, "New Employee Onboarding" title, organized checklist sections with checkboxes, timeline indicators, and responsible party fields. A4 portrait (3:4) with 10mm margins. CMYK-safe colours. Print-ready.',
  'orientation-presentation': 'This is an ORIENTATION PRESENTATION slide design. Create a branded presentation slide template with: company logo, professional layout with content areas, and brand colour scheme. Use brand colours for the slide master with accent elements, subtle background patterns, and professional typography hierarchy. The design must feel engaging and informative. Landscape orientation (16:9).',

  // ── STATIONERY CATEGORY GUIDANCE ──

  'business-card': 'This is a BUSINESS CARD / VISITING CARD design shown COMPLETELY FLAT and FACE-ON — as it appears when printed and laid flat on a surface. NOT as a 3D mockup, NOT at an angle, NOT tilted, NOT floating with drop shadows, NOT standing up on edge. The ENTIRE card face must be visible straight-on with zero perspective. Both front and back should be considered — use brand colours with elegant typography, generous white space, and refined visual hierarchy. Include areas for: name, title, phone, email, website, and company logo. Standard business card size (3.5 × 2 inches / 89 × 51 mm). 3mm safe margin for all critical content. Full bleed backgrounds to the edge. CMYK-safe colours only — no neon or electric RGB colours. Solid opaque fills, no transparency effects. The design must look like a finished print file from a professional studio — flat, sharp, clean, directly printable.',
  'letterhead': 'This is a CORPORATE LETTERHEAD design shown COMPLETELY FLAT — as it appears when printed on paper, NOT as a 3D paper mockup or document with perspective. Create a professional letterhead with a refined header area featuring the company logo, name, and contact details. Use brand colours elegantly in the header strip and footer. The body area must have generous white space for content. Include subtle watermark or background pattern for brand presence. A4 portrait (3:4) with 20mm top margin for header, 15mm side and bottom margins. CMYK-safe brand colours. Solid opaque header and footer fills. Crisp, legible typography at print size. Print-ready for office laser printing.',
  'envelope-a4': 'This is an A4 ENVELOPE design shown COMPLETELY FLAT — as it appears when printed, NOT as a 3D envelope mockup with perspective or flap shadow. Create a branded A4 envelope with company logo, return address, and subtle background pattern or watermark. Use brand colours for the header area and return address section. A4 envelope proportions (3:4). 5mm safe margins for critical content. CMYK-safe colours. Solid fills. Print-ready.',
  'envelope-dl': 'This is a DL ENVELOPE design shown COMPLETELY FLAT — as it appears when printed, NOT as a 3D envelope mockup. Create a branded DL envelope with company logo and return address. Use brand colours strategically — not overwhelming but clearly present. DL envelope proportions (3:4). 5mm safe margins. CMYK-safe colours. Solid fills. Print-ready.',
  'email-signature': 'This is an EMAIL SIGNATURE design. Create a professional, clean email signature design with areas for: name, title, company, phone, email, website, and company logo. Use brand colours sparingly for maximum impact. The signature must look good at email width and be legible at small sizes. Horizontal layout (16:9 ratio).',
  'presentation-template': 'This is a PRESENTATION SLIDE TEMPLATE design. Create a branded presentation template with: title slide layout, content slide layout, and section divider layout. Use brand colours for slide master backgrounds, accent bars, and typography hierarchy. The template must feel professional and engaging — suitable for pitches, reports, and board presentations. Landscape orientation (16:9 ratio).',

  'invoice-template': 'This is an INVOICE TEMPLATE design shown FLAT — as it appears when printed on paper. Create a professional, clean invoice template with: company header/logo, client information area, itemized table layout, subtotal/tax/total section, and payment details footer. A4 portrait (3:4) with 10mm safe margins. CMYK-safe brand colours in header and accent lines. Solid fills. Clean grid, legible at print size. Print-ready.',
  'quotation-template': 'This is a QUOTATION TEMPLATE design shown FLAT — as it appears when printed on paper. Create a professional quotation/estimate template with: company header, client details, itemized pricing table, terms section, and call-to-action area. A4 portrait (3:4) with 10mm margins. CMYK-safe brand colours. Solid fills. Print-ready.',
  'receipt-design': 'This is a RECEIPT DESIGN shown FLAT — as it appears when printed. Create a branded receipt with: company header/logo, transaction details area, itemized list, total section, and footer. A4 portrait (3:4) with 10mm margins. CMYK-safe colours. Print-ready.',
  'purchase-order': 'This is a PURCHASE ORDER TEMPLATE design shown FLAT — as it appears when printed. Create a professional purchase order template with: company header, vendor details, order table, terms and conditions, and authorization section. A4 portrait (3:4) with 10mm margins. CMYK-safe brand colours. Solid fills. Print-ready.',
  'billing-format': 'This is a BILLING FORMAT design shown FLAT — as it appears when printed. Create a professional billing format with: company header, billing details, itemized charges, payment terms, and payment methods section. A4 portrait (3:4) with 10mm margins. CMYK-safe brand colours. Print-ready.',
  'proposal-template': 'This is a PROPOSAL TEMPLATE design shown FLAT — as it appears when printed. Create a compelling, professional proposal template with: branded cover page, executive summary section, services/details area, pricing table, and terms section. A4 portrait (3:4) with 15mm margins. CMYK-safe brand colours throughout. Solid fills, no transparency effects. Print-ready.',

  'thank-you-card': 'This is a THANK YOU CARD design shown COMPLETELY FLAT — as it appears when printed and laid flat. NOT as a 3D card mockup. Create an elegant, warm card with: company logo, "Thank You" heading, and space for a personal message. Landscape orientation (4:3). 3mm safe margins. CMYK-safe brand colours. Solid fills. Print-ready.',
  'warranty-card': 'This is a WARRANTY CARD design shown COMPLETELY FLAT — as it appears when printed. Create a professional warranty card with: company logo, product information section, warranty terms, and validation area (date, serial number, stamp). Landscape orientation (4:3). 3mm safe margins. CMYK-safe colours. Solid fills. Print-ready.',
  'instruction-manual': 'This is an INSTRUCTION MANUAL cover design shown COMPLETELY FLAT — as it appears when printed, NOT as a 3D book mockup. Create a branded cover with: company logo, product name/number area, "User Guide" title, and clean layout. A4 portrait (3:4) with 10mm margins. CMYK-safe brand colours. Print-ready.',
  'product-insert-card': 'This is a PRODUCT INSERT CARD design shown COMPLETELY FLAT — as it appears when printed. Create a branded insert card for product packaging with: welcome message, quick start tips, warranty info, or cross-sell messaging. Landscape orientation (4:3). 3mm safe margins. CMYK-safe brand colours. Solid fills. Print-ready.',
  'branded-stickers': 'This is a BRANDED STICKERS design sheet shown FLAT — as it appears when printed on sticker paper, NOT as 3D stickers with shadows. Create a set of branded sticker designs featuring: company logo, tagline, mascot or icon variations, and decorative brand elements. Use brand colours vibrantly — stickers should be eye-catching. Multiple sticker designs in a grid layout. Square format (1:1). CMYK-safe colours (use vivid but printable colours, not neon). Print-ready.',
  'packaging-tape': 'This is a PACKAGING TAPE design shown FLAT — as a horizontal strip for printing, NOT as a 3D tape roll mockup. Create a branded packaging tape design with: repeating company logo, tagline, and brand pattern across the tape width. Must work as a continuous repeating strip. Brand colours prominently displayed. Landscape orientation (16:9). CMYK-safe bold colours. Print-ready.',

  'stamps': 'This is a BRANDED STAMP design shown FLAT — as it appears when stamped on paper, NOT as a 3D rubber stamp mockup. Create a stamp design with: company logo, company name, and address. Bold, thick lines that reproduce clearly when stamped. Single-colour or two-colour design. CMYK-safe. No fine detail that fills in when inked. Square format (1:1). Print-ready.',
  'branding-print': 'This is a BRANDING PRINT design shown FLAT — as it appears when printed. Create a comprehensive brand identity print sheet showcasing: logo variations, colour palette, typography samples, and brand pattern. Use brand colours vibrantly with professional layout. Landscape orientation (4:3). CMYK-safe colours. Print-ready brand reference piece.',
  'standees-print': 'This is a STANDEE / ROLL-UP BANNER design shown COMPLETELY FLAT — as it appears when printed and unrolled, NOT as a 3D standee mockup. Create a tall, eye-catching design with: company logo at top, key message or headline, product/service imagery area, and contact information at bottom. Keep logo and headline in upper 40% (visible above crowd). Contact info in bottom 15%. 5cm safe margins on sides, 10cm top/bottom. CMYK-safe bold colours for distance visibility. Solid fills. Print-ready for large-format production.',
  'booth-designs': 'This is an EXHIBITION BOOTH DESIGN shown FLAT — as a flat panel design for print production, NOT as a 3D booth mockup. Create a branded exhibition booth panel design with: company logo prominently displayed, product showcase areas, tagline, and contact information. Brand colours at large scale for maximum visibility. Landscape orientation (16:9). CMYK-safe bold colours. Print-ready for large-format production.',
  't-shirts': 'This is a BRANDED T-SHIRT DESIGN shown FLAT — as a flat print design for the chest area, NOT as a 3D t-shirt mockup on a person or hanger. Create a branded t-shirt design with: company logo, tagline, and visual elements. The design must work on fabric — use bold, solid colours that reproduce well in screen printing or DTG. Keep design within chest print area (approximately 30 × 36 cm max). Portrait orientation (3:4). CMYK-safe bold colours. No fine halftone details that fill in on fabric. Print-ready.',
  'notebook': 'This is a CORPORATE NOTEBOOK / DIARY COVER design shown COMPLETELY FLAT — as it appears when printed, NOT as a 3D notebook mockup. Create a branded notebook cover with: company logo prominently placed, company name, subtle brand pattern or texture, and elegant typography. The design must work for both hardcover and softcover formats. Use brand colours with a professional, executive feel. Portrait orientation (3:4). CMYK-safe colours. Solid fills. Print-ready.',
  'coffee-mug': 'This is a BRANDED COFFEE MUG / TUMBLER design shown FLAT — as a flat wrap-around print design for the mug surface, NOT as a 3D mug mockup. Create a branded mug design with: company logo centered, tagline or brand pattern as secondary elements. The design must work on a cylindrical surface — avoid text that wraps more than halfway around. Use bold, solid colours that reproduce well in sublimation or screen printing. Landscape orientation (16:9) representing the wrap area. CMYK-safe bold colours. Print-ready.',
  'tote-bag': 'This is a BRANDED TOTE BAG design shown FLAT — as a flat print design for the bag front, NOT as a 3D tote bag mockup. Create a branded tote bag design with: company logo, tagline, and visual elements. The design must work on cotton canvas — use bold, solid colours with high contrast that reproduce well in screen printing. Keep design within the printable area (approximately 25 × 30 cm). Portrait orientation (3:4). CMYK-safe bold colours. No fine halftone details. Print-ready.',
  'newsletter-template': 'This is a NEWSLETTER TEMPLATE design shown FLAT — as it appears when printed. Create a branded newsletter layout with: header with company logo, article sections with clear hierarchy, sidebar for quick links, and footer. A4 portrait (3:4) with 10mm margins. CMYK-safe brand colours for header and accent elements. Solid fills. Print-ready.',
  'brochure-pdf': 'This is a BROCHURE DESIGN shown COMPLETELY FLAT — as it appears when printed and laid flat, NOT as a 3D folded brochure mockup with perspective. Create a professional tri-fold brochure design with: compelling front cover, product/service sections, company information, and call-to-action panel. Each panel approximately 99 × 210 mm. 5mm safe margins per panel. CMYK-safe colours throughout. Solid fills, no transparencies. Ensure fold positions align with panel boundaries. Print-ready with crisp, legible text at actual size.',
  'pitch-deck': 'This is a PITCH DECK slide design. Create a branded pitch deck cover slide with: company logo, compelling headline area, and visual impact. Use brand colours with dramatic composition and professional depth. The design must feel confident, innovative, and investment-worthy. Landscape orientation (16:9 ratio).',
  'marketing-collateral': 'This is a MARKETING COLLATERAL design shown FLAT — as it appears when printed. Create a professional marketing piece with: company branding, promotional messaging, product highlights, and call-to-action. Use brand colours with visual impact and professional composition. Landscape orientation (4:3). 5mm safe margins. CMYK-safe colours. Solid fills. Print-ready.',
};

// ============================================
// FULL-PAGE DOCUMENT CATEGORIES
// ============================================

/**
 * Asset categories that are printed as a full page/sheet (A4 or similar) where the
 * artwork must fill the ENTIRE image frame edge-to-edge — the page IS the canvas.
 * These need an explicit "no floating sheet / no surrounding background / no white
 * space around the edges" rule so documents like invoices come out print-ready and
 * fully aligned to the page. Merch and object designs (t-shirts, mugs, stickers,
 * stamps, tape) are intentionally EXCLUDED — those centre a graphic on a plain field.
 */
export const FULL_PAGE_DOCUMENT_CATEGORIES: Set<string> = new Set([
  // Stationery — page/document formats
  'letterhead', 'envelope-a4', 'envelope-dl',
  'invoice-template', 'quotation-template', 'receipt-design', 'purchase-order',
  'billing-format', 'proposal-template', 'instruction-manual', 'newsletter-template',
  // HR — page/document formats
  'attendance-sheet', 'internal-memo', 'notepad', 'offer-letter', 'relieving-letter',
  'appointment-letter', 'handbook', 'code-of-conduct', 'onboarding-checklist',
  'experience-certificate', 'appreciation-certificate', 'training-certificate',
  'completion-certificate', 'internship-certificate',
]);

/** True when the asset is a full-page document that must fill the frame edge-to-edge. */
export function isFullPageDocumentCategory(assetCategory: string | undefined): boolean {
  return !!assetCategory && FULL_PAGE_DOCUMENT_CATEGORIES.has(assetCategory);
}

// ============================================
// BUILD SYSTEM PROMPT
// ============================================

function buildSystemPrompt(inputs: ImageEnhancementInputs, overrides?: PromptOverrides): string {
  const hasBrandContext = inputs.brandName || inputs.brandStrategy || inputs.visualIdentity || inputs.businessDescription;
  const assetCategoryGuidance = overrides?.assetCategoryGuidance || ASSET_CATEGORY_GUIDANCE;
  const hasAssetType = inputs.assetCategory && assetCategoryGuidance[inputs.assetCategory];
  const isMinimalInput = !inputs.description || inputs.description.trim().length < 20;
  const isPrintPlatform = inputs.platform === 'Print';
  const isFullPageDoc = isFullPageDocumentCategory(inputs.assetCategory);

  return `You are an elite brand image prompt engineer with deep expertise in creating production-ready, visually sophisticated image generation prompts for DALL-E 3 and similar models.

Your task is to transform the provided context into an optimised, richly detailed image-generation prompt that produces premium-quality, professional results that look like they were created by a skilled graphic designer — NOT generic AI illustrations.${hasBrandContext ? '\n\nCRITICAL: You have rich brand context available. You MUST deeply incorporate this brand data into every aspect of the prompt — colours, tone, personality, positioning, visual style, typography, mood, and audience. The brand context is the FOUNDATION of the prompt, not optional background. Every visual detail must trace back to the brand identity.' : ''}${isMinimalInput ? '\n\nIMPORTANT: The user provided minimal or no description. You MUST generate a complete, detailed prompt by inferring ALL necessary visual details from the brand context, asset type, and platform requirements. Do NOT simply repeat what little the user wrote — expand it into a comprehensive, professional prompt using every piece of available context. Add specific composition, lighting, texture, and atmospheric details that a professional designer would include.' : ''}${hasAssetType ? '\n\nASSET TYPE EXPERTISE: You deeply understand the specific requirements, best practices, and quality standards for this asset type. Apply professional design principles rigorously.' : ''}

PRODUCTION-READY REQUIREMENTS — this is NON-NEGOTIABLE:
- The generated image MUST be a COMPLETE, FINISHED design that can be downloaded and used immediately without ANY modifications, edits, or post-processing
- The image MUST be clearly and immediately recognizable as the specific asset type requested — a business card must look unmistakably like a business card, a letterhead like a letterhead, etc.
- Every visual element must be fully rendered with professional detail — no placeholder areas, no "Lorem ipsum" text, no "Your Name Here" labels, no sample/generic content
- The design must include ALL content elements specific to that asset type (logo areas, text fields, contact info zones, decorative borders, seal areas, signature lines, etc.) as clearly defined layout zones with professional placeholder styling
- The output must look indistinguishable from a design produced by a professional graphic design studio using tools like Adobe Illustrator or Figma — not a rough concept or wireframe

ASSET-SPECIFIC CONTENT REQUIREMENTS:
- Generate ONLY the specific asset type requested — do not produce a generic image that could be anything
- The design must follow the structural conventions of the specific asset type (e.g., business cards have front/back layouts with specific information zones, certificates have border/seal/signature areas, letterheads have header/footer zones)
- Include appropriate placeholder text areas that look realistic and professional (e.g., "John Smith" for names, "Acme Corporation" for company names, "contact@company.com" for emails) — these must look like real content, not wireframe labels
- Apply asset-type-specific professional standards: correct aspect ratios, appropriate margins and bleed areas, realistic content density, proper visual hierarchy for the asset's purpose
${isPrintPlatform ? `\n\nPRINT-READY REQUIREMENTS — this is NON-NEGOTIABLE for print assets:
- The design MUST be shown COMPLETELY FLAT and FACE-ON — as it would appear when printed and laid on a table. NOT as a 3D mockup, NOT at an angle, NOT with perspective distortion, NOT floating with drop shadows suggesting a physical object, NOT with the card tilted or standing up. The entire design surface must be visible straight-on with zero perspective.
- The design MUST be print-ready: suitable for direct professional printing without any modifications, edits, or post-processing
- Use ONLY CMYK-safe colours: avoid neon greens, electric blues, bright magentas, and any colours that shift or dull in CMYK conversion. Prefer rich but printable colours (deep navy, burgundy, forest green, warm gold, charcoal, copper, etc.)
- Maintain safe margins: all critical content (text, logos, contact information, signatures, seals) must stay within the inner 85-90% of the frame — nothing important near the edges where trimming occurs
- Extend all backgrounds, colour fills, and decorative borders fully to the edge of the frame (implicit bleed) — never leave a thin white border unless it is an intentional design choice
- Use solid, opaque fills only — no screen-mode blending (multiply, overlay, screen), no transparency effects, no CSS-like opacity layers that do not reproduce in print
- Typography must be crisp, well-sized, and legible at actual print dimensions — no tiny text that becomes illegible when printed
- Avoid ALL digital-only visual effects: no screen glows, no RGB light rays, no neon flares, no glass/refraction effects, no digital bokeh overlays, no HUD-style elements
- The output must look like a finished print production file from a professional design studio — NOT a digital mockup, NOT a screen preview, NOT a 3D render, NOT a concept sketch
- Design for physical print material characteristics: subtle paper texture feel where appropriate, ink coverage considerations, clean vector-like edges, flat professional layout` : ''}${isFullPageDoc ? `\n\nFULL-PAGE DOCUMENT REQUIREMENTS — this is NON-NEGOTIABLE for this asset (e.g. invoice, quotation, letterhead, certificate):
- A4 PROPORTION: Lay the document out as a standard A4 page in portrait orientation (unless the asset is explicitly landscape, such as a certificate). The content must be composed for A4 page proportions.
- FILL THE ENTIRE FRAME EDGE-TO-EDGE: The document itself must occupy 100% of the image canvas — the four edges of the image ARE the four edges of the printed page (the trim line). The page fills the whole image with nothing around it.
- NO FLOATING SHEET / NO MOCKUP: Do NOT render the document as a sheet of paper lying on a desk, table, floor, wall, clipboard, or any surface. Do NOT show the paper as a smaller rectangle placed inside a larger scene. Do NOT add a coloured, textured, gradient, or photographic background around or behind the page.
- ZERO SURROUNDING WHITE SPACE: There must be NO empty margin, padding, canvas, frame, border, or blank area around the document on any side (top, bottom, left, or right). The only white space allowed is the document's own internal page margins (the paper's white body), never a gap between the page and the image edge.
- NO 3D / NO PERSPECTIVE / NO SHADOW: The page must be perfectly flat, straight-on, and 2D — like a vector/PDF export viewed at 100%. No tilt, no angle, no perspective, no curling corners, no drop shadow under the page, no realistic paper-thickness or 3D rendering of any kind.
- The header/branding extends fully to the top edge of the page and the footer to the bottom edge; backgrounds and colour bands bleed to the page edges. Keep critical text within the page's internal safe margins, but the page itself touches all four image edges.
- The result must look exactly like opening a finished, print-ready document file — the page and the image are one and the same, flat and full-bleed.
- THIS OVERRIDES any guidance below about depth, dimension, lighting, shadows, foreground/midground/background, or atmospheric effects: for this full-page document, DISREGARD all of that and keep the entire layout strictly flat, clean, and 2D.` : ''}
1. Professional and polished — not flat, simple, or generic
2. Visually sophisticated — with depth, dimension, texture, and atmospheric quality
3. Brand-consistent — colours, mood, and style must match the brand identity precisely
4. Production-ready — suitable for real-world commercial use, not a concept sketch

COMPOSITION GUIDELINES — include specific direction for:
- Lighting: Specify the type (dramatic, soft, rim, ambient, golden hour, studio) and direction
- Depth: Include foreground, midground, and background elements for dimension
- Texture: Describe surface qualities, material feel, and tactile details
- Colour harmony: Reference specific brand colours and how they interact
- Visual weight: Direct the eye through the composition with intentional hierarchy

AVOID these common AI art pitfalls:
- Flat, solid-colour backgrounds with no depth or texture
- Generic stock-photo aesthetics with no personality
- Simple gradient fills without compositional sophistication
- Overly symmetrical or static compositions lacking dynamism
- Missing atmospheric effects (shadows, light rays, depth of field, subtle gradients)
- Wireframe-style layouts with "Your text here" or "Sample" labels
- Incomplete designs that look like concepts rather than finished products

OUTPUT RULES:
- Output ONLY the image generation prompt as plain text. No JSON, no markdown, no explanations, no labels, no section headers.
- The prompt must be a single, cohesive, flowing paragraph (max 800 words).
- Include specific visual details: composition, lighting, colour palette, mood, perspective, texture, atmosphere.
- If brand colours are provided, explicitly reference them in the prompt with how they should be used (primary, accent, background tones).
- Match the artistic style precisely with specific visual cues and technical terminology.
- Optimise for the target platform's specific requirements.
- Avoid text in images unless specifically requested by the user.
- Do not include any brand logos, trademarked elements, or copyrighted characters unless explicitly part of the brand context.
- Make the prompt vivid, specific, and descriptive enough that the image generator produces a production-ready, premium result.
- Ensure the prompt reads naturally as a single flowing description — do NOT use labeled sections or bullet points in the output.
- The resulting image must look like it was created by a professional graphic designer, not a generic AI art generator.
- The design must be COMPLETE and READY TO USE — no missing elements, no placeholder zones that look unfinished, no areas that require manual editing.`;
}

// ============================================
// HELPER: Format brand context into rich text
// ============================================

function formatColorPalette(colorPalette: any): string | null {
  if (!colorPalette) return null;
  if (typeof colorPalette === 'string') return colorPalette;
  if (typeof colorPalette === 'object') {
    const entries = Object.entries(colorPalette)
      .filter(([, v]) => v && typeof v === 'string')
      .map(([k, v]) => `${k}: ${v}`);
    return entries.length > 0 ? entries.join(', ') : null;
  }
  return null;
}

function formatTypography(typography: any): string | null {
  if (!typography) return null;
  if (typeof typography === 'string') return typography;
  if (typeof typography === 'object') {
    const entries = Object.entries(typography)
      .filter(([, v]) => v && typeof v === 'string')
      .map(([k, v]) => `${k}: ${v}`);
    return entries.length > 0 ? entries.join(', ') : null;
  }
  return null;
}

function formatStringOrArray(val: string[] | string | undefined | null): string | null {
  if (!val) return null;
  return Array.isArray(val) ? val.join(', ') : val;
}

// ============================================
// ASSET CONTENT ELEMENTS MAP
// ============================================

/**
 * Maps asset category values to the specific content elements
 * that MUST appear in a production-ready design for that asset type.
 * This ensures generated images include realistic, professional
 * placeholder content rather than blank areas or wireframe labels.
 */
export const ASSET_CONTENT_ELEMENTS: Record<string, string> = {
  // ── Visual Identity ──
  'logo': 'a distinctive icon/symbol or wordmark, brand name, optional tagline area',
  'secondary-logo': 'a simplified or alternate logo mark, brand name in secondary layout, secondary colour treatment, compact composition recognisable alongside the primary logo',
  'wordmark': 'brand name in custom typography, distinctive letterforms or ligatures, brand colour treatment, typographic logo that IS the brand identity',
  'logo-icon': 'a bold, recognizable icon/symbol mark, simplified brand shape',
  'favicon': 'a bold, clear icon representation of the brand, high-contrast shape',
  'app-icon': 'a polished icon with dimensional depth, brand symbol or letter, gradient background',
  'brandPattern': 'a repeating seamless pattern with brand motifs, colours, and visual rhythm',
  'backgroundImage': 'an atmospheric background with depth, gradient layers, subtle brand elements',
  'watermark': 'a semi-transparent brand mark or logo overlay, elegant opacity treatment',
  'virtual-background': 'a professional video call background with subtle brand logo placement, soft gradient in brand colours, elegant office-like atmosphere, clear centre safe zone for speaker',
  'social-og': 'a compelling social card with headline area, visual focal point, brand colour background',
  'social-twitter': 'an attention-grabbing card with strong visual hierarchy, brand accent colours',
  'social-linkedin': 'a professional card with authority and credibility, clean layout, brand header',
  'social-instagram': 'a visually stunning square composition with dramatic lighting and brand mood',
  'social-facebook': 'an engaging share card with clear focal point, brand colours, and visual impact',
  'social-tiktok': 'a bold vertical composition with high contrast, energy, and brand vibrancy',
  'social-youtube': 'a high-impact thumbnail with dramatic composition, clear subject, and brand accent',

  // ── Web/Email/Presentation ──
  'web-banner': 'a cinematic hero banner with headline area, brand logo, atmospheric depth, and content zones',
  'email-header': 'a polished header bar with company logo, navigation hints, and brand accent strip',
  'email-footer': 'a clean footer with company info, social icons, unsubscribe area, and brand colours',
  'presentation': 'a branded slide with title area, content zones, brand accent bar, and professional layout',
  'document': 'a professional document template with branded header, content area, and footer',

  // ── HR Assets ──
  'id-card-front': 'photo placeholder area (circular or square), full name, job title, department, employee ID number, company logo, company name, barcode or QR code zone',
  'id-card-back': 'emergency contact section, "If found return to" section with company address, barcode area, magnetic strip zone, blood group field',
  'lanyard-design': 'repeating brand logo and/or tagline pattern, brand colour strip, clip/attachment area at bottom, safety breakaway indication',
  'employee-badge': 'photo placeholder, employee name, title/role, department, company logo and name, badge number area',
  'visiting-card': 'front: name, title, company logo, phone, email, website; back: company logo or tagline with clean design',
  'attendance-sheet': 'company header/logo area, month/year field, date columns, employee name rows, signature/in-out time fields',
  'internal-memo': 'company header with logo, "MEMORANDUM" title, To/From/Date/Subject fields, body content area, footer with company info',
  'notepad': 'company logo in header, subtle brand watermark or pattern in background, lined or blank note area, footer with company contact',
  'diary-planner': 'elegant cover with company logo, brand colour accents, date/calendar sections, note areas, premium material feel',
  'file-folder': 'company logo on tab and front panel, brand colour accent strip, label area for folder title, professional finish',
  'document-folder': 'company logo prominently on front, brand colour panels, spine label area, inside pocket indication',
  'pen-branding': 'branded pen design with company logo on barrel, brand colours, tagline area, product mockup view',
  'desk-name-plate': 'employee name area, title/department line, company logo, professional desk-mount design',
  'offer-letter': 'company header/logo area, "Offer of Employment" title, candidate details section, position and salary area, terms section, signature zone',
  'experience-certificate': 'decorative border, company logo/seal area, "Certificate of Experience" title, employee name, duration, role description, date, authorised signature area, stamp/seal zone',
  'appreciation-certificate': 'ornamental border, company logo, "Certificate of Appreciation" title, recipient name, achievement description, date, signature lines, seal area, celebratory accents',
  'training-certificate': 'structured border, company logo, "Certificate of Training" title, trainee name, course/program name, completion date, authorised signature area, seal/stamp zone, gold accents',
  'completion-certificate': 'elegant border, company seal/logo area, "Certificate of Completion" title, recipient name, program/course details, completion date, authorising signatures, prominent seal area',
  'internship-certificate': 'clean border, company logo, "Internship Certificate" title, intern name, department, duration, project details, supervisor signature area, professional formatting',
  'relieving-letter': 'company header/logo area, "Relieving Letter" title, employee details section, last working day, clearance confirmation, formal sign-off area, company seal zone',
  'appointment-letter': 'company header/logo area, "Letter of Appointment" title, candidate details section, position and terms area, acceptance zone, signature areas, company seal zone',
  'welcome-kit': 'branded kit box or folder overview with company branding, checklist of included items, warm welcome message area, company colours prominently',
  'handbook': 'professional handbook cover with company logo, "Employee Handbook" title, edition/year, subtle brand pattern background, authoritative feel',
  'code-of-conduct': 'professional document header with company logo, "Code of Conduct" title, structured section indicators, brand colour accents, authoritative and trustworthy layout',
  'onboarding-checklist': 'branded checklist template with company header/logo, "New Employee Onboarding" title, organized checkbox sections, timeline indicators, responsible party fields',
  'orientation-presentation': 'branded presentation slide template with company logo, professional layout with content areas, brand colour scheme, engaging visual elements',

  // ── Stationery ──
  'business-card': 'front: full name, job title, company logo, phone number, email address, website URL; back: company logo or tagline, social media handles, additional contact info — all with professional placeholder text',
  'letterhead': 'company logo and name in header area, contact details (address, phone, email, website) in header/footer, date line, reference area, subtle watermark, branded footer with company registration details',
  'envelope-a4': 'company logo and name, return address, stamp/indicia area, brand colour accent strip along flap, subtle background pattern or watermark',
  'envelope-dl': 'company logo and return address on front, brand colour on flap edge, professional layout with address window area indication',
  'email-signature': 'full name, job title, company name and logo, phone number, email address, website URL, social media icons, professional horizontal layout',
  'presentation-template': 'branded title slide with company logo and presentation title area, content slide with header bar and bullet zones, section divider slide, brand colour scheme throughout',
  'invoice-template': 'company header with logo and details, client information area, invoice number and date, itemized table with columns (description, quantity, rate, amount), subtotal/tax/total section, payment terms, bank details footer',
  'quotation-template': 'company header with logo, client details section, quotation number and date, itemized pricing table, terms and conditions section, valid-until date, call-to-action area, signature zone',
  'receipt-design': 'company header/logo, receipt number and date, itemized list with amounts, total section, payment method, thank you message, footer with return policy',
  'purchase-order': 'company header with logo, PO number and date, vendor details section, itemized order table with quantities and prices, terms and conditions, authorization signature area',
  'billing-format': 'company header, billing details section, itemized charges table, payment terms and methods, subtotal/tax/total section, company bank details, professional layout',
  'proposal-template': 'branded cover page with company logo and title, executive summary section, table of contents area, services/details sections, pricing table, terms section, signature area, professional formatting throughout',
  'thank-you-card': 'company logo, "Thank You" headline, personal message area, warm closing, brand colours with celebratory feel, inside/outside design consideration',
  'warranty-card': 'company logo and name, product information section, warranty terms area, serial number/date fields, validation stamp zone, customer service contact info',
  'instruction-manual': 'branded cover with company logo, product name/number, "User Guide" title, section dividers, numbered steps areas, diagram placeholders, professional formatting',
  'product-insert-card': 'branded card with welcome message, product highlights area, QR code or website link, warranty info section, social media handles, premium unboxing feel',
  'branded-stickers': 'multiple sticker designs on one sheet: company logo sticker, tagline sticker, icon stickers, decorative brand element stickers — each clearly delineated in a grid layout',
  'packaging-tape': 'repeating pattern of company logo, tagline, and brand colours across the tape width, seamless continuous design, professional packaging feel',
  'stamps': 'company logo and name, address text, professional circular or rectangular rubber stamp design, bold clear text, ink impression style',
  'branding-print': 'brand identity sheet showcasing: logo variations, primary and secondary colour palette swatches, typography samples (heading, body, accent), brand pattern sample, professional layout',
  'standees-print': 'tall standee/roll-up banner with company logo at top, headline or key message, product/service visual area, contact information at bottom, bold brand colours for visibility from distance',
  'booth-designs': 'exhibition booth with large company logo, product showcase areas, key messaging zones, interactive element indications, contact/QR code area, dramatic brand presence',
  't-shirts': 'front design area with company logo and/or tagline, brand colour on fabric indication, neckline detail, professional mockup view showing design on garment',
  'notebook': 'notebook cover with company logo centred, company name, subtle brand pattern, elegant typography, spine detail, professional executive feel',
  'coffee-mug': 'mug wrap design with company logo, tagline or brand pattern, bold solid colours for sublimation printing, landscape wrap-around layout',
  'tote-bag': 'tote bag front panel with company logo, tagline, decorative brand elements, bold high-contrast design for screen printing on canvas',
  'newsletter-template': 'branded header with company logo and name, article sections with headlines and body text areas, sidebar for quick links, call-to-action buttons, footer with unsubscribe and company info',
  'brochure-pdf': 'tri-fold brochure with: compelling front cover, inside panels with product/service details, company information panel, contact/call-to-action panel, back cover — professional layout throughout',
  'pitch-deck': 'branded title slide with company logo and compelling headline, subtitle area, brand colour scheme, professional layout with visual impact, investment-worthy feel',
  'marketing-collateral': 'branded marketing piece with headline area, key messaging zones, product/service highlights, call-to-action, brand colours and visual elements throughout, professional and persuasive layout',

  // ── Other ──
  'other': 'a clearly defined, professional design with appropriate content zones, brand elements, and realistic placeholder content — must look finished and ready to use',
};

/**
 * Get the content elements string for a given asset category.
 * Returns null if no specific elements are defined for the category.
 */
function getAssetContentElements(assetCategory: string | undefined, overrides?: PromptOverrides): string | null {
  if (!assetCategory) return null;
  const contentElements = overrides?.assetContentElements || ASSET_CONTENT_ELEMENTS;
  return contentElements[assetCategory] || null;
}

// ============================================
// BUILD USER PROMPT
// ============================================

function buildUserPrompt(inputs: ImageEnhancementInputs, overrides?: PromptOverrides): string {
  const parts: string[] = [];
  const isMinimalInput = !inputs.description || inputs.description.trim().length < 20;
  const assetCategoryGuidance = overrides?.assetCategoryGuidance || ASSET_CATEGORY_GUIDANCE;
  const assetGuidance = inputs.assetCategory ? assetCategoryGuidance[inputs.assetCategory] : null;
  const hasBrandContext = inputs.brandName || inputs.brandStrategy || inputs.visualIdentity || inputs.businessDescription;

  // ── Core description ──
  // When minimal input, build a rich description from brand context
  if (isMinimalInput && hasBrandContext) {
    const brandRef = inputs.brandName ? `for "${inputs.brandName}"` : '';
    const assetType = assetGuidance
      ? inputs.assetCategory?.replace(/-/g, ' ')
      : 'brand asset';
    const bizDesc = inputs.businessDescription ? ` — ${inputs.businessDescription}` : '';
    const industry = inputs.businessIndustry ? ` in the ${inputs.businessIndustry} industry` : '';
    const personality = inputs.brandPersonality?.length ? ` embodying ${inputs.brandPersonality.join(', ')}` : '';
    const archetype = inputs.brandArchetype ? ` as a ${inputs.brandArchetype} brand` : '';

    parts.push(`Create a professional, premium-quality ${assetType} ${brandRef}${industry}${personality}${archetype}${bizDesc}. The design must be production-ready, visually striking, and immediately recognizable — sophisticated enough for real-world commercial use, not a simple concept sketch.`);
  } else {
    parts.push(`IMAGE DESCRIPTION: ${inputs.description}`);
  }

  // ── Asset type guidance (always include for brand assets) ──
  if (assetGuidance) {
    parts.push(`\nASSET TYPE REQUIREMENT: ${assetGuidance}`);
  }

  // ── Asset-specific content completeness ──
  // Every generated design must include the content elements typical of that asset type
  const contentElements = getAssetContentElements(inputs.assetCategory, overrides);
  if (contentElements) {
    parts.push(`\nREQUIRED CONTENT ELEMENTS: This ${inputs.assetCategory?.replace(/-/g, ' ') || 'asset'} design MUST include clearly defined layout zones for: ${contentElements}. Each zone must be professionally styled with realistic placeholder content (e.g., "John Smith" for names, "Acme Corp" for company names). The design must look COMPLETE and READY TO USE — no blank placeholder areas, no wireframe labels, no "Your Text Here" labels.`);
  }

  // ── Objective ──
  if (inputs.objective) {
    parts.push(`OBJECTIVE/PURPOSE: ${inputs.objective}`);
  }

  // ── Style guidance with brand personality integration ──
  const styleGuide = (overrides?.styleGuidance || STYLE_GUIDANCE)[inputs.style] || inputs.style;
  const brandPersonalityStyle = inputs.brandPersonality?.length
    ? ` that reflects ${inputs.brandPersonality.join(', ')} personality`
    : '';
  const brandArchetypeStyle = inputs.brandArchetype
    ? ` embodying the ${inputs.brandArchetype} archetype`
    : '';
  parts.push(`ART STYLE: ${inputs.style} — ${styleGuide}${brandPersonalityStyle}${brandArchetypeStyle}`);

  // ── Target audience (enriched with ICP and brand strategy) ──
  const audienceParts: string[] = [];
  if (inputs.targetAudience) audienceParts.push(inputs.targetAudience);
  if (inputs.icpDescription) audienceParts.push(inputs.icpDescription);
  if (inputs.businessIndustry && !inputs.targetAudience) audienceParts.push(`professionals in ${inputs.businessIndustry}`);
  if (inputs.brandStrategy?.positioning && !inputs.targetAudience) audienceParts.push(`aligned with ${inputs.brandStrategy.positioning}`);
  if (audienceParts.length > 0) {
    parts.push(`TARGET AUDIENCE: ${audienceParts.join('. ')}`);
  }

  // ── Platform guidance ──
  const platformMap = overrides?.platformGuidance || PLATFORM_GUIDANCE;
  const platformInfo = platformMap[inputs.platform] || platformMap.Other || PLATFORM_GUIDANCE.Other;
  parts.push(`PLATFORM/CHANNEL: ${inputs.platform} — For ${platformInfo.usage}. Tips: ${platformInfo.tips}`);

  // ── Aspect ratio ──
  parts.push(`ASPECT RATIO: ${inputs.aspectRatio}`);

  // ── Additional instructions ──
  if (inputs.additionalInstructions) {
    parts.push(`ADDITIONAL INSTRUCTIONS: ${inputs.additionalInstructions}`);
  }

  // ── Design Brief — synthesise brand data into a coherent direction ──
  if (hasBrandContext) {
    const briefParts: string[] = [];

    // Brand identity
    if (inputs.brandName) briefParts.push(`Brand: "${inputs.brandName}"`);
    if (inputs.brandColors?.length) briefParts.push(`Primary Colours: ${inputs.brandColors.join(', ')} — these must dominate the colour scheme`);
    if (inputs.brandTone) briefParts.push(`Brand Tone: ${inputs.brandTone}`);
    if (inputs.brandPersonality?.length) briefParts.push(`Personality: ${inputs.brandPersonality.join(', ')}`);
    if (inputs.brandArchetype) briefParts.push(`Archetype: ${inputs.brandArchetype}`);

    // Business context
    if (inputs.businessDescription) briefParts.push(`Business: ${inputs.businessDescription}`);
    if (inputs.businessIndustry) briefParts.push(`Industry: ${inputs.businessIndustry}`);

    if (briefParts.length > 0) {
      parts.push(`\nDESIGN BRIEF:\n${briefParts.join('\n')}`);
    }
  }

  // ── Founder Context (humanises the brand) ──
  if (inputs.founderNames?.length) {
    const founderParts: string[] = [];
    founderParts.push(`Founders: ${inputs.founderNames.join(', ')}`);
    if (inputs.founderBios?.length) {
      founderParts.push(`Founder Story: ${inputs.founderBios.join('. ')}`);
    }
    if (inputs.founderResponsibilityAreas?.length) {
      founderParts.push(`Leadership: ${inputs.founderResponsibilityAreas.join(', ')}`);
    }
    parts.push(`\nFOUNDER CONTEXT (reflect the founder's vision and personality in the design):\n${founderParts.join('\n')}`);
  }

  // ── Brand SOP 1.7 — Visual Direction and Guardrails ──
  if (inputs.brandVisualDirection || inputs.brandConsistencyGuardrails || inputs.brandForbiddenDesignPatterns?.length) {
    const guardParts: string[] = [];
    if (inputs.brandVisualDirection) guardParts.push(`Visual Direction: ${inputs.brandVisualDirection}`);
    if (inputs.brandVisualTheme) guardParts.push(`Visual Theme: ${inputs.brandVisualTheme}`);
    if (inputs.brandConsistencyGuardrails) {
      const g = inputs.brandConsistencyGuardrails;
      if (g.cannotChange?.length) guardParts.push(`NEVER CHANGE: ${g.cannotChange.join('; ')}`);
      if (g.canEvolve?.length) guardParts.push(`CAN EVOLVE: ${g.canEvolve.join('; ')}`);
      if (g.misuseExamples?.length) guardParts.push(`MISUSE EXAMPLES (avoid these patterns): ${g.misuseExamples.join('; ')}`);
    }
    if (inputs.brandForbiddenDesignPatterns?.length) {
      guardParts.push(`FORBIDDEN DESIGN PATTERNS — Never use: ${inputs.brandForbiddenDesignPatterns.join(', ')}`);
    }
    if (guardParts.length > 0) {
      parts.push(`\nBRAND GUARDRAILS (these rules are NON-NEGOTIABLE — the design MUST respect them):\n${guardParts.join('\n')}`);
    }
  }

  // ── Brand Strategy ──
  if (inputs.brandStrategy) {
    const strategyParts: string[] = [];
    if (inputs.brandStrategy.mission) strategyParts.push(`Mission: ${inputs.brandStrategy.mission}`);
    if (inputs.brandStrategy.vision) strategyParts.push(`Vision: ${inputs.brandStrategy.vision}`);
    if (inputs.brandStrategy.values) strategyParts.push(`Core Values: ${formatStringOrArray(inputs.brandStrategy.values)}`);
    if (inputs.brandStrategy.positioning) strategyParts.push(`Positioning: ${inputs.brandStrategy.positioning}`);
    if (inputs.brandStrategy.differentiators) strategyParts.push(`Differentiators: ${formatStringOrArray(inputs.brandStrategy.differentiators)}`);
    if (inputs.brandStrategy.personalityTraits) strategyParts.push(`Personality: ${formatStringOrArray(inputs.brandStrategy.personalityTraits)}`);
    if (inputs.brandStrategy.voiceTone) strategyParts.push(`Voice & Tone: ${inputs.brandStrategy.voiceTone}`);
    if (strategyParts.length > 0) {
      parts.push(`\nBRAND STRATEGY (infuse these into the visual design):\n${strategyParts.join('\n')}`);
    }
  }

  // ── Visual Identity (the most critical section for image generation) ──
  if (inputs.visualIdentity) {
    const visualParts: string[] = [];
    const colorStr = formatColorPalette(inputs.visualIdentity.colorPalette);
    if (colorStr) {
      // Merge brand colors and visual identity colors for maximum specificity
      const allColors = inputs.brandColors?.length
        ? `${inputs.brandColors.join(', ')} (brand) + ${colorStr} (visual identity)`
        : colorStr;
      visualParts.push(`Colour Palette: ${allColors} — use these exact colours throughout the design as the dominant colour scheme`);
    } else if (inputs.brandColors?.length) {
      visualParts.push(`Colour Palette: ${inputs.brandColors.join(', ')} — these brand colours MUST dominate the design`);
    }
    const fontStr = formatTypography(inputs.visualIdentity.typography);
    if (fontStr) visualParts.push(`Typography Reference: ${fontStr}`);
    if (inputs.visualIdentity.designPrinciples) visualParts.push(`Design Principles: ${formatStringOrArray(inputs.visualIdentity.designPrinciples)}`);
    if (inputs.visualIdentity.moodDescription) visualParts.push(`Mood & Atmosphere: ${inputs.visualIdentity.moodDescription}`);
    if (inputs.visualIdentity.visualStyle) visualParts.push(`Visual Style: ${inputs.visualIdentity.visualStyle}`);
    if (visualParts.length > 0) {
      parts.push(`\nVISUAL IDENTITY (the design MUST follow these guidelines strictly):\n${visualParts.join('\n')}`);
    }
  } else if (inputs.brandColors?.length) {
    // No visual identity but brand colours exist
    parts.push(`\nBRAND COLOURS: ${inputs.brandColors.join(', ')} — these colours MUST be prominently featured throughout the design`);
  }

  // ── Brand Guidelines ──
  if (inputs.brandGuidelines) {
    const guidelinesParts: string[] = [];
    if (inputs.brandGuidelines.voiceGuidelines) {
      const vg = inputs.brandGuidelines.voiceGuidelines;
      if (typeof vg === 'object' && vg !== null) {
        const entries = Object.entries(vg).filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`);
        if (entries.length > 0) guidelinesParts.push(`Voice Guidelines: ${entries.join(', ')}`);
      } else if (typeof vg === 'string') {
        guidelinesParts.push(`Voice Guidelines: ${vg}`);
      }
    }
    if (inputs.brandGuidelines.designRules) {
      const dr = inputs.brandGuidelines.designRules;
      if (typeof dr === 'object' && dr !== null) {
        const entries = Object.entries(dr).filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`);
        if (entries.length > 0) guidelinesParts.push(`Design Rules: ${entries.join(', ')}`);
      } else if (typeof dr === 'string') {
        guidelinesParts.push(`Design Rules: ${dr}`);
      }
    }
    if (inputs.brandGuidelines.dosAndDonts) {
      const dd = inputs.brandGuidelines.dosAndDonts;
      if (Array.isArray(dd)) guidelinesParts.push(`Dos and Don'ts: ${dd.join('; ')}`);
      else if (typeof dd === 'string') guidelinesParts.push(`Dos and Don'ts: ${dd}`);
    }
    if (guidelinesParts.length > 0) {
      parts.push(`\nBRAND GUIDELINES (adhere to these rules):\n${guidelinesParts.join('\n')}`);
    }
  }

  // ── Brand Manual ──
  if (inputs.brandManual) {
    const manualParts: string[] = [];
    if (inputs.brandManual.summary) manualParts.push(`Overview: ${inputs.brandManual.summary}`);
    if (inputs.brandManual.usageStandards) {
      const us = inputs.brandManual.usageStandards;
      if (typeof us === 'object' && us !== null) {
        const entries = Object.entries(us).filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`);
        if (entries.length > 0) manualParts.push(`Usage Standards: ${entries.join(', ')}`);
      } else if (typeof us === 'string') {
        manualParts.push(`Usage Standards: ${us}`);
      }
    }
    if (manualParts.length > 0) {
      parts.push(`\nBRAND MANUAL:\n${manualParts.join('\n')}`);
    }
  }

  // ── Quality Directives ──
  parts.push('\nQUALITY DIRECTIVES: This must be a COMPLETE, PRODUCTION-READY design that can be downloaded and used IMMEDIATELY without any modifications, edits, or post-processing. The design must be clearly and immediately recognizable as the specific asset type requested — it should look like a finished professional design, NOT a concept, wireframe, or rough draft. Professional, polished, sophisticated composition with depth, dimension, and visual hierarchy. Include atmospheric depth — layered foreground, midground, and background elements. Rich textures and material qualities. Intentional lighting with highlights and shadows that create dimension. NO flat solid backgrounds, NO generic stock-photo aesthetics, NO simple gradients without compositional sophistication, NO placeholder text that says "Your Text Here" or "Sample", NO unfinished areas that require manual editing.');

  // ── Print-ready directives (for Print platform) ──
  if (inputs.platform === 'Print') {
    parts.push('\nPRINT-READY DIRECTIVES: This design must be shown COMPLETELY FLAT and FACE-ON — as it would appear when printed and laid flat on a surface. NOT as a 3D mockup, NOT at an angle, NOT tilted, NOT floating with drop shadows suggesting a physical card or paper standing up. The entire design surface must be visible straight-on with zero perspective. The design must be PRINT-READY and suitable for direct professional printing without any modifications. Use CMYK-safe colours only (no neon, no electric RGB-only colours, no colours that shift in CMYK conversion). Keep all critical content (text, logos, signatures, contact info, seals) within safe margins (inner 85-90% of the frame). Extend backgrounds to the full edge for bleed. Use solid opaque fills — no transparency effects, no screen-mode blending, no multiply/overlay/screen blends. No digital-only effects (screen glows, RGB light effects, glass reflections, digital bokeh overlays). Typography must be crisp and legible at actual print size. The output must look like a finished print production file from a professional design studio, NOT a digital mockup or screen preview.');
  }

  // ── User instructions for re-enhancement ──
  if (inputs.userInstructions) {
    parts.push(`\nUSER FEEDBACK: ${inputs.userInstructions}`);
  }

  // ── Asset category group ──
  if (inputs.assetTypeCategory) {
    parts.push(`ASSET CATEGORY GROUP: ${inputs.assetTypeCategory.replace(/-/g, ' ')}`);
  }

  // ── Specific requirements ──
  if (inputs.assetRequirements) {
    parts.push(`SPECIFIC REQUIREMENTS: ${inputs.assetRequirements}`);
  }

  // ── Closing instruction ──
  if (isMinimalInput && hasBrandContext) {
    parts.push('\nGenerate a single, detailed, brand-aligned image generation prompt that creates a COMPLETE, PRODUCTION-READY result with visual sophistication and depth. Use ALL the brand context above to specify exact colours, mood, style, composition, lighting, perspective, texture, and atmosphere. The output must look like it was created by a professional designer who deeply understands this brand — with depth, dimension, and visual richness. The design must be FINISHED and READY TO USE immediately after download — no placeholders, no blank areas, no text that says "Your Text Here" or "Sample Content". Every element must look like real, professional content.');
  } else {
    parts.push('\nGenerate a single, detailed, brand-aligned image generation prompt with professional composition, atmospheric lighting, textural depth, and visual sophistication. The result must be a COMPLETE, PRODUCTION-READY design — finished, polished, and usable immediately after download without any modifications. No placeholder areas, no wireframe labels, no "Your Text Here" text. Every visual element must be fully rendered with professional detail and realistic content.');
  }

  return parts.join('\n\n');
}

// ============================================
// EXPORTED FUNCTIONS
// ============================================

/**
 * Build the system prompt and user prompt for Ollama prompt enhancement.
 */
export interface PromptOverrides {
  styleGuidance?: Record<string, string>;
  platformGuidance?: Record<string, { usage: string; tips: string }>;
  assetCategoryGuidance?: Record<string, string>;
  assetContentElements?: Record<string, string>;
}

export function buildEnhancementPrompts(inputs: ImageEnhancementInputs, overrides?: PromptOverrides): PromptResult {
  return {
    systemPrompt: buildSystemPrompt(inputs, overrides),
    userPrompt: buildUserPrompt(inputs, overrides),
    maxTokens: 1200,
  };
}

/**
 * Build a fallback prompt from the user's inputs without AI enhancement.
 * Used when Ollama is unavailable.
 */
export function buildFallbackPrompt(inputs: ImageEnhancementInputs, overrides?: PromptOverrides): string {
  const parts: string[] = [];
  const isMinimalInput = !inputs.description || inputs.description.trim().length < 20;
  const assetCategoryGuidance = overrides?.assetCategoryGuidance || ASSET_CATEGORY_GUIDANCE;
  const assetGuidance = inputs.assetCategory ? assetCategoryGuidance[inputs.assetCategory] : null;

  // Core description — enrich from context when minimal
  if (isMinimalInput && (inputs.brandName || inputs.businessDescription)) {
    const brandRef = inputs.brandName ? ` for "${inputs.brandName}"` : '';
    const assetType = assetGuidance ? inputs.assetCategory?.replace(/-/g, ' ') : 'brand asset';
    parts.push(`Professional, premium-quality ${assetType} design${brandRef}`);
    if (inputs.businessDescription) parts.push(`(${inputs.businessDescription})`);
    if (inputs.brandPersonality?.length) parts.push(`embodying ${inputs.brandPersonality.join(', ')} personality`);
  } else {
    parts.push(inputs.description);
  }

  // Style
  const styleGuide = (overrides?.styleGuidance || STYLE_GUIDANCE)[inputs.style] || inputs.style;
  parts.push(`${inputs.style} style — ${styleGuide}`);

  // Brand colours — always include when available
  if (inputs.brandColors?.length) {
    parts.push(`using brand colours: ${inputs.brandColors.join(', ')} as dominant palette`);
  } else if (inputs.visualIdentity?.colorPalette) {
    const colorStr = formatColorPalette(inputs.visualIdentity.colorPalette);
    if (colorStr) parts.push(`using brand colours: ${colorStr} as dominant palette`);
  }

  // Platform
  const platformMap = overrides?.platformGuidance || PLATFORM_GUIDANCE;
  const platformInfo = platformMap[inputs.platform] || platformMap.Other || PLATFORM_GUIDANCE.Other;
  parts.push(`designed for ${inputs.platform} (${platformInfo.usage})`);

  // Target audience
  const audienceParts: string[] = [];
  if (inputs.targetAudience) audienceParts.push(inputs.targetAudience);
  if (inputs.icpDescription) audienceParts.push(inputs.icpDescription);
  if (audienceParts.length > 0) parts.push(`targeting ${audienceParts.join(' and ')}`);

  // Objective
  if (inputs.objective) parts.push(`purpose: ${inputs.objective}`);

  // Additional instructions
  if (inputs.additionalInstructions) parts.push(inputs.additionalInstructions);

  // Brand strategy (condensed for fallback)
  if (inputs.brandStrategy) {
    const bs = inputs.brandStrategy;
    if (bs.positioning) parts.push(`brand positioning: ${bs.positioning}`);
    if (bs.voiceTone) parts.push(`voice: ${bs.voiceTone}`);
    if (bs.values) parts.push(`values: ${formatStringOrArray(bs.values)}`);
    if (bs.differentiators) parts.push(`differentiators: ${formatStringOrArray(bs.differentiators)}`);
  }

  // Visual identity (condensed for fallback)
  if (inputs.visualIdentity) {
    const vi = inputs.visualIdentity;
    if (vi.moodDescription) parts.push(`mood: ${vi.moodDescription}`);
    if (vi.visualStyle) parts.push(`visual style: ${vi.visualStyle}`);
    const fontStr = formatTypography(vi.typography);
    if (fontStr) parts.push(`typography: ${fontStr}`);
  }

  // Brand personality
  if (inputs.brandPersonality?.length) {
    parts.push(`personality: ${inputs.brandPersonality.join(', ')}`);
  }

  // Brand archetype
  if (inputs.brandArchetype) {
    parts.push(`archetype: ${inputs.brandArchetype}`);
  }

  // Quality directives for fallback
  parts.push('professional, polished, production-ready design with depth and visual sophistication — COMPLETE and READY TO USE immediately after download, no blank placeholders, no wireframe labels, no "Your Text Here" text');

  // Print-ready directives for fallback
  if (inputs.platform === 'Print') {
    parts.push('shown COMPLETELY FLAT and FACE-ON as it appears when printed, NOT as a 3D mockup or tilted perspective. PRINT-READY: suitable for direct professional printing, CMYK-safe colours only (no neon or electric RGB-only colours), safe margins for critical content (inner 85-90%), backgrounds extended to full edge for bleed, solid opaque fills only, no digital-only effects (screen glows, RGB light, glass reflections, digital bokeh), crisp legible typography at print size, finished print production file — NOT a digital mockup');
  }

  // Asset category guidance for fallback
  if (assetGuidance) {
    parts.push(assetGuidance);
  }

  // Asset-specific content elements for fallback
  const contentElements = getAssetContentElements(inputs.assetCategory, overrides);
  if (contentElements) {
    parts.push(`Must include clearly defined layout zones for: ${contentElements}. Each zone must have realistic, professional placeholder content`);
  }

  return parts.join('. ') + '.';
}