"""
Prompt templates for zero-shot classification with LLaMA
"""

from ..constants import NICHE_CLASSES, POPULARITY_CLASSES


def create_influencer_niche_prompt(biography: str, recent_captions: str, recent_hashtags: str) -> str:
    """
    Create prompt for influencer niche classification

    Args:
        biography: Influencer biography
        recent_captions: Concatenated recent captions
        recent_hashtags: Concatenated recent hashtags

    Returns:
        Formatted prompt string
    """
    # Truncate inputs to avoid token limits (LLaMA context window)
    bio_preview = biography[:300] if biography else "No bio"
    captions_preview = recent_captions[:800] if recent_captions else "No captions"
    hashtags_preview = recent_hashtags[:300] if recent_hashtags else "No hashtags"

    # Check if we have enough context
    has_bio = bool(biography and len(biography.strip()) > 10)
    has_captions = bool(recent_captions and len(recent_captions.strip()) > 20)
    has_hashtags = bool(recent_hashtags and len(recent_hashtags.strip()) > 5)

    context_quality = sum([has_bio, has_captions, has_hashtags])

    prompt = f"""You are a social media analyst. Classify this Instagram influencer's niche based on their content.

PROFILE DATA:
Bio: {bio_preview}
Recent Posts: {captions_preview}
Hashtags: {hashtags_preview}

CONTEXT QUALITY: {"Sufficient" if context_quality >= 2 else "Limited - be cautious"}

TASK: Determine the top 3 most likely niches from this list:
Fashion, Fitness, Food, Travel, Lifestyle, Beauty, Tech, Gaming, Sports, Music, Art, Photography, Comedy, Business, Education, Health, Parenting, Other

RULES:
1. Analyze the content themes, keywords, and topics
2. If context is LIMITED or UNCLEAR:
   - Use "Other" as the top niche with high probability (0.7+)
   - Add "Lifestyle" as secondary (0.2)
   - Indicate uncertainty by spreading remaining probability
3. If context is SUFFICIENT:
   - Return the top 3 most likely niches with probabilities
   - Highest probability should be >0.5 if you're confident
   - Use lower probabilities (0.3-0.4) if uncertain
4. Probabilities must sum to 1.0
5. Use this EXACT JSON format (no extra text):

{{"Fashion": 0.6, "Lifestyle": 0.3, "Beauty": 0.1}}

IMPORTANT: If you cannot determine a clear niche due to lack of context, return:
{{"Other": 0.7, "Lifestyle": 0.2, "Business": 0.1}}

Your JSON response:"""

    return prompt


def create_influencer_popularity_prompt(
    followers: int,
    engagement_rate: float,
    verified: bool,
    avg_likes: float,
    avg_comments: float
) -> str:
    """
    Create prompt for influencer popularity tier classification

    Uses comprehensive metrics analysis instead of just follower count:
    - Follower count (base indicator)
    - Engagement rate (quality indicator)
    - Actual likes/comments (authenticity indicator)
    - Comment-to-like ratio (community depth indicator)
    - Bot detection signals (fake follower indicator)

    Args:
        followers: Follower count
        engagement_rate: Engagement rate percentage
        verified: Verification status
        avg_likes: Average likes per post
        avg_comments: Average comments per post

    Returns:
        Formatted prompt string
    """
    # Calculate quality metrics for context
    expected_engagement = followers * (engagement_rate / 100) if followers > 0 else 0
    actual_engagement = avg_likes + (avg_comments * 3)
    quality_ratio = actual_engagement / expected_engagement if expected_engagement > 0 else 0

    comment_to_like_ratio = (avg_comments / avg_likes * 100) if avg_likes > 0 else 0


    prompt = f"""Classify this influencer's popularity tier based on their metrics and quality.
    
INSTRUCTIONS:
1. Use the following standard tier definitions as a ROBUST BASELINE:
   - Nano: <10,000 followers
   - Micro: 10,000 - 100,000 followers
   - Mid: 100,000 - 500,000 followers
   - Macro: 500,000 - 1,000,000 followers
   - Mega: >1,000,000 followers

2. CONSIDER QUALITY ADJUSTMENTS:
   - You may UPGRADE a tier if engagement is exceptional (>5%) or they are verified.
   - You MUST DOWNGRADE a tier if there are strong signals of fake followers (e.g., quality_ratio < 0.5 or comment_to_like_ratio < 0.5%).

INFLUENCER DATA:
- Followers: {followers:,}
- Engagement Rate: {engagement_rate:.2f}%
- Verified: {'Yes' if verified else 'No'}
- Avg Likes: {avg_likes:,.0f}
- Avg Comments: {avg_comments:,.0f}
- Quality Ratio: {quality_ratio:.2f} (Expected: 1.0)
- Comment-to-Like Ratio: {comment_to_like_ratio:.2f}%

TASK:
1. Assign a probability to EACH of the 5 tiers.
2. Probabilities MUST sum to exactly 1.0.
3. Return ONLY valid JSON.

CRITICAL FORMAT - Return ONLY this JSON:
{{"Nano": 0.X, "Micro": 0.X, "Mid": 0.X, "Macro": 0.X, "Mega": 0.X}}

JSON:"""

    return prompt


def create_business_niche_prompt(business_description: str) -> str:
    """
    Create prompt for business niche classification
    
    Args:
        business_description: Business description text
        
    Returns:
        Formatted prompt string
    """
    niche_list = ", ".join(NICHE_CLASSES)
    
    prompt = f"""You are an expert at analyzing business requirements and matching them to influencer niches.

Analyze the following business description:

{business_description}

Based on this business description, determine which influencer niches would be most relevant for this business.

Choose from these niches:
{niche_list}

Provide confidence scores (between 0 and 1) for the top 3 most relevant niches. The scores should sum to approximately 1.0.

Respond ONLY with valid JSON in this exact format:
{{
  "Fashion": 0.0,
  "Fitness": 0.0,
  "Food": 0.0
}}

JSON Response:"""
    
    return prompt


def create_business_popularity_prompt(budget_min: float, budget_max: float) -> str:
    """
    Create prompt for business budget to popularity tier mapping

    Uses dynamic pricing model that accounts for follower count variations
    within tiers (especially important for Mega tier: 1M vs 10M vs 100M followers)

    Args:
        budget_min: Minimum budget
        budget_max: Maximum budget

    Returns:
        Formatted prompt string
    """
    from .pricing import get_tier_from_budget

    # Calculate average budget and get tier probabilities
    avg_budget = (budget_min + budget_max) / 2
    _, tier_probabilities = get_tier_from_budget(budget_min, budget_max)

    # Format probabilities for display
    prob_display = ", ".join([f"{tier}: {prob:.2f}" for tier, prob in tier_probabilities.items() if prob > 0])

    prompt = f"""You are an influencer marketing pricing expert. Match this budget to influencer tiers.

BUDGET RANGE: ${budget_min:,.2f} - ${budget_max:,.2f} (Average: ${avg_budget:,.2f})

DYNAMIC PRICING MODEL (price per post varies by follower count):

Nano Tier (<10K followers):
  • 1K followers: ~$10-$15
  • 5K followers: ~$50-$75
  • 9K followers: ~$90-$135

Micro Tier (10K-100K followers):
  • 10K followers: ~$100-$150
  • 50K followers: ~$500-$750
  • 100K followers: ~$1,000-$1,500

Mid Tier (100K-500K followers):
  • 100K followers: ~$1,000-$1,500
  • 250K followers: ~$2,500-$3,750
  • 500K followers: ~$5,000-$7,500

Macro Tier (500K-1M followers):
  • 500K followers: ~$5,000-$7,500
  • 750K followers: ~$10,000-$15,000
  • 1M followers: ~$15,000-$25,000

Mega Tier (>1M followers) - HIGHLY VARIABLE:
  • 1M-2M followers: ~$25,000-$50,000
  • 2M-5M followers: ~$50,000-$125,000
  • 5M-10M followers: ~$125,000-$250,000
  • 10M-50M followers: ~$250,000-$1,000,000
  • 50M+ followers: ~$1,000,000+ (celebrity pricing)

CALCULATED TIER PROBABILITIES:
Based on budget ${avg_budget:,.2f}, the overlap analysis suggests: {prob_display}

INSTRUCTIONS:
1. Return probabilities for ALL 5 tiers (must sum to 1.0)
2. Consider that budget ${avg_budget:,.2f} can afford influencers in multiple tiers
3. Higher probability to tiers where budget is in the middle of the range
4. Lower probability to tiers where budget is at the edge
5. Zero probability only if budget is completely outside tier range

EXACT JSON FORMAT (no extra text):
{{"Nano": 0.0, "Micro": 0.0, "Mid": 0.0, "Macro": 0.0, "Mega": 0.0}}

JSON:"""

    return prompt

