<?php

namespace App\Services\AI\Concerns;

/**
 * Shared guardrail clause appended to every generation prompt (image, Veo, Sora) so
 * creatives are safe to publish in an ad campaign without manual fact-checking: no
 * invented product claims, no accidental third-party branding, no garbled on-screen
 * text, no anatomy/continuity artifacts.
 */
trait BuildsProductionSafePrompts
{
    private function productionGuardrails(): string
    {
        return 'Cinematic 4K broadcast commercial aesthetic. Anatomically precise, authentic natural skin texture, accurate hands, and consistent continuous lighting. Depict only verified product features stated above. No unintended on-screen graphic text or captions.';
    }

    /** Video-only addition to productionGuardrails(): clear audio + accurate enunciation. */
    private function audioAndTextGuardrails(): string
    {
        return 'Audio is clear, studio-grade speech with articulate enunciation in the stated accent. Speak at a calm, natural conversational pace. Pronounce separated capital letters individually and say "dot com" as words. Deliver the complete dialogue cleanly before the clip ends, leaving a natural visual reaction pause and nod before the final frame. The presenter maintains natural, synchronized lip movement.';
    }

    private function normalizeSpokenText(string $text): string
    {
        $text = preg_replace_callback(
            '/\b([A-Za-z][A-Za-z0-9-]*)\.(com|net|org|io|ai)\b/i',
            static function (array $matches): string {
                $name = preg_replace('/(?<=[a-z])(?=[A-Z])/', ' ', $matches[1]);

                return str_replace('-', ' ', $name).' dot '.strtolower($matches[2]);
            },
            $text,
        );
        $text = preg_replace_callback('/\b(?:[A-Z]\.){2,}[A-Z]?\.?/', static function (array $matches): string {
            return implode(' ', str_split(str_replace('.', '', $matches[0])));
        }, $text);
        $text = preg_replace_callback('/\b[A-Z]{2,6}\b/', static function (array $matches): string {
            return implode(' ', str_split($matches[0]));
        }, $text);
        $text = preg_replace('/(\d+(?:\.\d+)?)\s*%/', '$1 percent', $text);
        $text = str_replace(['&', '—', '–'], [' and ', ', ', ', '], $text);

        // Sanitize Responsible AI (RAI) safety filter triggers (violence, harm, sensitive bodily terms)
        $text = preg_replace('/\b(kills?|killing)\b/i', 'disrupts', $text);
        $text = preg_replace('/\b(deadly|fatal)\b/i', 'serious', $text);
        $text = preg_replace('/\b(sweat(?:ing)?\s+through)\b/i', 'overheating in', $text);

        return preg_replace('/\s+/', ' ', trim($text));
    }
}
