import type { Message } from "../_core/llm.ts";
import { invokeLLM } from "../_core/llm.ts";
import { generateImage } from "../_core/imageGeneration.ts";

export interface SocialMediaGenerationRequest {
  platform: "twitter" | "instagram" | "tiktok" | "facebook";
  topic: string;
  tone: "professional" | "casual" | "humorous" | "motivational";
  includeHashtags?: boolean;
  includeEmoji?: boolean;
  callToAction?: string;
  imageStyle?: string;
}

export interface GeneratedSocialPost {
  caption: string;
  hashtags: string[];
  mentions: string[];
  callToAction?: string;
  imagePrompt: string;
}

export class AISocialMediaService {
  /**
   * Generate social media post content for a specific platform
   */
  static async generatePost(
    request: SocialMediaGenerationRequest
  ): Promise<GeneratedSocialPost> {
    const systemPrompt = this.buildSystemPrompt(request.platform, request.tone);
    const userPrompt = this.buildUserPrompt(request);

    const messages: Message[] = [
      { role: "system", content: systemPrompt },
      { role: "user", content: userPrompt },
    ];

    const response = await invokeLLM({
      messages,
      response_format: {
        type: "json_schema",
        json_schema: {
          name: "social_post",
          strict: true,
          schema: {
            type: "object",
            properties: {
              caption: { type: "string", description: "Main post caption/text" },
              hashtags: {
                type: "array",
                items: { type: "string" },
                description: "Relevant hashtags",
              },
              mentions: {
                type: "array",
                items: { type: "string" },
                description: "Accounts to mention",
              },
              callToAction: {
                type: "string",
                description: "Call to action text",
              },
              imagePrompt: {
                type: "string",
                description: "Detailed prompt for image generation",
              },
            },
            required: ["caption", "hashtags", "mentions", "imagePrompt"],
          },
        },
      },
    });

    const content = response.choices[0].message.content;
    if (typeof content !== "string") {
      throw new Error("Invalid LLM response format");
    }

    const postData = JSON.parse(content) as GeneratedSocialPost;
    return postData;
  }

  /**
   * Generate multiple posts for a campaign
   */
  static async generateCampaignPosts(
    campaignTopic: string,
    platforms: ("twitter" | "instagram" | "tiktok" | "facebook")[],
    postCount: number = 5,
    tone: "professional" | "casual" | "humorous" | "motivational" = "casual"
  ): Promise<Record<string, GeneratedSocialPost[]>> {
    const results: Record<string, GeneratedSocialPost[]> = {};

    for (const platform of platforms) {
      const posts: GeneratedSocialPost[] = [];

      for (let i = 0; i < postCount; i++) {
        const post = await this.generatePost({
          platform,
          topic: `${campaignTopic} (Post ${i + 1}/${postCount})`,
          tone,
          includeHashtags: true,
          includeEmoji: platform !== "twitter", // Twitter has character limits
          callToAction: "Join CoinKrazy today!",
          imageStyle: this.getImageStyleForPlatform(platform),
        });

        posts.push(post);
      }

      results[platform] = posts;
    }

    return results;
  }

  /**
   * Generate image for social media post
   */
  static async generatePostImage(
    imagePrompt: string,
    platform: "twitter" | "instagram" | "tiktok" | "facebook"
  ): Promise<string> {
    const platformSpecificPrompt = this.enhancePromptForPlatform(imagePrompt, platform);

    const { url } = await generateImage({
      prompt: platformSpecificPrompt,
    });

    return url;
  }

  /**
   * Build system prompt for social media generation
   */
  private static buildSystemPrompt(
    platform: string,
    tone: string
  ): string {
    const platformGuidelines = this.getPlatformGuidelines(platform);

    return `You are an expert social media marketing specialist for a casino gaming platform (CoinKrazy).
    You create engaging, compliant, and platform-optimized content.
    
    Platform: ${platform}
    Tone: ${tone}
    
    ${platformGuidelines}
    
    Guidelines:
    - Keep content engaging and shareable
    - Include relevant hashtags and mentions
    - Ensure compliance with gaming regulations
    - Encourage responsible gaming
    - Use platform-specific best practices
    - Include clear call-to-action when appropriate
    
    Always respond with valid JSON matching the specified schema.`;
  }

  /**
   * Build user prompt for social media generation
   */
  private static buildUserPrompt(request: SocialMediaGenerationRequest): string {
    return `Create a social media post for ${request.platform} about: ${request.topic}
    
    Requirements:
    - Tone: ${request.tone}
    - Include hashtags: ${request.includeHashtags ? "Yes" : "No"}
    - Include emoji: ${request.includeEmoji ? "Yes" : "No"}
    - Call to action: ${request.callToAction || "Encourage engagement"}
    - Image style: ${request.imageStyle || "Professional and engaging"}
    
    Please generate:
    1. An engaging caption optimized for ${request.platform}
    2. Relevant hashtags (5-10)
    3. Accounts to mention (2-3)
    4. A detailed image generation prompt
    5. Optional call-to-action text
    
    Ensure the content is platform-appropriate, engaging, and follows responsible gaming principles.`;
  }

  /**
   * Get platform-specific guidelines
   */
  private static getPlatformGuidelines(platform: string): string {
    const guidelines: Record<string, string> = {
      twitter: `- Max 280 characters for main text
      - Use relevant hashtags (2-3)
      - Keep it concise and punchy
      - Include link if needed`,
      instagram: `- Can use longer captions (up to 2,200 characters)
      - Use 20-30 relevant hashtags
      - Include emojis for engagement
      - Focus on visual storytelling`,
      tiktok: `- Create trend-aware content
      - Use trending sounds and hashtags
      - Keep it entertaining and short
      - Include trending challenges`,
      facebook: `- Longer-form content works well (100-500 characters)
      - Use 5-10 hashtags
      - Include emojis for personality
      - Encourage comments and shares`,
    };

    return guidelines[platform] || "";
  }

  /**
   * Get image style for platform
   */
  private static getImageStyleForPlatform(
    platform: "twitter" | "instagram" | "tiktok" | "facebook"
  ): string {
    const styles: Record<string, string> = {
      twitter: "Square, 1:1 ratio, professional, clean design",
      instagram: "Square or vertical, 1:1 or 4:5 ratio, vibrant, eye-catching",
      tiktok: "Vertical, 9:16 ratio, dynamic, trend-focused",
      facebook: "Square or landscape, 1:1 or 16:9 ratio, engaging, shareable",
    };

    return styles[platform] || "Professional and engaging";
  }

  /**
   * Enhance image prompt for platform-specific requirements
   */
  private static enhancePromptForPlatform(
    basePrompt: string,
    platform: "twitter" | "instagram" | "tiktok" | "facebook"
  ): string {
    const dimensions: Record<string, string> = {
      twitter: "1024x1024 pixels, square format",
      instagram: "1080x1080 pixels, square format",
      tiktok: "1080x1920 pixels, vertical format",
      facebook: "1200x628 pixels, landscape format",
    };

    return `${basePrompt}
    
    Platform specifications: ${dimensions[platform]}
    Style: Modern, casino-appropriate, engaging, high-quality
    Brand: CoinKrazy Sweepstakes Casino
    Include: Gaming elements, excitement, fun
    Avoid: Misleading claims, excessive gambling imagery`;
  }
}
