import type { AIContext } from "./ai-context";
import type { FitnessProfile } from "../database/types";
import { formatGoalForPrompt } from "./ai-context";

/**
 * Build enhanced AI prompt with comprehensive user context
 * Includes profile, goals, progress, and recommendation history
 */
export function buildEnhancedPrompt(context: AIContext): string {
  const {
    profile,
    activeGoals,
    completedGoals,
    recentRecommendations,
    progressSummary,
  } = context;

  // Build goals section
  const activeGoalsText =
    activeGoals.length > 0
      ? activeGoals.map((g) => `- ${formatGoalForPrompt(g)}`).join("\n")
      : "- No active goals set";

  const completedGoalsText =
    completedGoals.length > 0
      ? completedGoals
          .slice(0, 3)
          .map((g) => g.title)
          .join(", ")
      : "None yet";

  // Build context about recent recommendations
  const recommendationContextText =
    recentRecommendations.length > 0
      ? `The user has received ${recentRecommendations.length} recommendations in the past week. Consider their progress and avoid repetitive advice.`
      : "This is a new user or they haven't received recent recommendations. Provide comprehensive guidance.";

  return `You are a professional fitness trainer and nutritionist with access to the user's complete fitness journey.

## User Profile
- Height: ${profile.height || "Not specified"} cm
- Weight: ${profile.weight || "Not specified"} kg
- Age: ${profile.age || "Not specified"}
- Gender: ${profile.gender || "Not specified"}
- Primary Goal: ${profile.fitnessGoals?.[0] || "General fitness"}
- Activity Level: ${profile.activityLevel || "Not specified"}
- Medical Conditions: ${profile.medicalConditions || "None"}
- Allergies: ${profile.allergies || "None"}
- Injuries: ${profile.injuries || "None"}

## Active Goals (${activeGoals.length})
${activeGoalsText}

## Recent Progress
- Goals Completed: ${progressSummary.goalsCompleted}
- Active Goals: ${progressSummary.goalsActive}
- Average Progress on Active Goals: ${progressSummary.averageProgress.toFixed(1)}%
${completedGoals.length > 0 ? `- Recently Completed: ${completedGoalsText}` : ""}

## Recommendation History
${recommendationContextText}

## Task
Generate a personalized daily recommendation that:
1. Acknowledges their progress on active goals
2. Provides specific, actionable steps toward goal completion
3. Builds on previous recommendations without being repetitive
4. Adapts to their current progress level
5. Takes into account their medical conditions, allergies, and injuries

Respond in the following JSON format ONLY, no other text. Do not use markdown formatting or code blocks:
{
  "recommendationText": "Personalized motivation and progress acknowledgment (2-3 sentences)",
  "activityPlan": "Specific workout plan aligned with active goals (detailed, 3-5 exercises or activities)",
  "dietPlan": "Nutrition plan supporting their goals and restrictions (detailed, include meals and portions)"
}`;
}

/**
 * Build basic prompt for users without complete context
 * Fallback when goals or other data is missing
 */
export function buildBasicPrompt(profile: FitnessProfile): string {
  return `You are a professional fitness trainer and nutritionist.
Generate a detailed daily recommendation for a user with the following profile:
- Height: ${profile.height} cm
- Weight: ${profile.weight} kg
- Age: ${profile.age}
- Gender: ${profile.gender}
- Goal: ${profile.fitnessGoals?.[0]}
- Activity Level: ${profile.activityLevel}
- Medical Conditions: ${profile.medicalConditions || "None"}
- Injuries: ${profile.injuries || "None"}

Please provide the response in the following JSON format ONLY, no other text. Do not use markdown formatting or code blocks:
{
  "recommendationText": "General advice and motivation for today.",
  "activityPlan": "Detailed workout or activity plan for today.",
  "dietPlan": "Detailed meal plan for today."
}`;
}
