/**
 * CV Prompt Builder Service
 * Constructs detailed prompts for AI CV generation
 */

export interface CVGenerationData {
  founder: any | null;
  businessProfile: any | null;
  interviews: any[];
  speaking: any[];
  funding: any[];
  presentations: any[];
  experience: any[];
  /** Education entries captured in wizard Step 2. Optional so existing callers still compile. */
  education?: any[];
  projects: any[];
}

/**
 * Build a comprehensive AI prompt for CV generation
 * @param data All available data sources
 * @returns Formatted prompt string
 */
export function buildCVPrompt(data: CVGenerationData): string {
  const { founder, businessProfile, interviews, speaking, funding, presentations, experience, education, projects } = data;

  const sections: string[] = [];

  // ============================================
  // PERSONAL INFORMATION
  // ============================================
  if (founder) {
    sections.push(`
## PERSONAL INFORMATION
- **Name:** ${founder.name || 'Not provided'}
- **Designation:** ${founder.designation || 'Not provided'}
- **Bio:** ${founder.bio || 'Not provided'}
- **Expertise:** ${founder.expertise?.join(', ') || 'Not provided'}
- **Email:** ${founder.email || 'Not provided'}
- **Phone:** ${founder.phone || 'Not provided'}
- **LinkedIn:** ${founder.socialProfiles?.linkedIn || 'Not provided'}
- **Other Social Profiles:**
${Object.entries(founder.socialProfiles || {})
  .filter(([key]) => !['linkedIn', 'website'].includes(key))
  .map(([key, value]) => `  - ${key}: ${value || 'Not provided'}`)
  .join('\n') || '  - None'}
- **Location:** ${[founder.city, founder.state, founder.country].filter(Boolean).join(', ') || 'Not provided'}
- **Responsibility Area:** ${founder.responsibilityArea || 'Not provided'}
`);
  }

  // ============================================
  // BUSINESS CONTEXT
  // ============================================
  if (businessProfile) {
    sections.push(`
## BUSINESS CONTEXT
- **Company Name:** ${businessProfile.name || 'Not provided'}
- **Industry:** ${businessProfile.primaryIndustry || businessProfile.industry || 'Not provided'}
- **Business Model:** ${businessProfile.businessModel || 'Not provided'}
- **Mission:** ${businessProfile.mission || 'Not provided'}
- **Vision:** ${businessProfile.vision || 'Not provided'}
- **Company Overview:** ${businessProfile.overview || businessProfile.description || 'Not provided'}
- **Founded:** ${businessProfile.startDate || businessProfile.foundedYear || 'Not provided'}
- **Team Size:** ${businessProfile.teamSize || businessProfile.employeeCount || 'Not provided'}
`);
  }

  // ============================================
  // INTERVIEWS & MEDIA APPEARANCES
  // ============================================
  if (interviews.length > 0) {
    sections.push(`
## INTERVIEWS & MEDIA APPEARANCES
${interviews.map((interview, index) => `
### Interview ${index + 1}
- **Type:** ${interview.type || 'N/A'}
- **Title/Topic:** ${interview.name || interview.contextTopic || 'N/A'}
- **Platform:** ${interview.platform || 'N/A'}
- **Date:** ${interview.createdAt ? new Date(interview.createdAt).toLocaleDateString() : 'N/A'}
- **Description:** ${interview.description || interview.contextTopic || 'N/A'}
- **Speaker:** ${interview.speakerName || 'N/A'}
- **Highlights:** ${interview.questions?.slice(0, 3).map((q: any) => q.question || q.text).join('; ') || 'N/A'}
`).join('\n')}
`);
  }

  // ============================================
  // SPEAKING ENGAGEMENTS
  // ============================================
  if (speaking.length > 0) {
    sections.push(`
## SPEAKING ENGAGEMENTS
${speaking.map((engagement, index) => `
### Speaking Engagement ${index + 1}
- **Title:** ${engagement.name || engagement.title || 'N/A'}
- **Type:** ${engagement.speechType || engagement.type || 'N/A'}
- **Event/Venue:** ${engagement.occasionContext || engagement.event || 'N/A'}
- **Date:** ${engagement.createdAt ? new Date(engagement.createdAt).toLocaleDateString() : 'N/A'}
- **Audience:** ${engagement.audienceType || engagement.audience || 'N/A'}
- **Duration:** ${engagement.duration || 'N/A'}
- **Topic:** ${engagement.topic || 'N/A'}
- **Description:** ${engagement.content?.slice(0, 200) || engagement.description || 'N/A'}
`).join('\n')}
`);
  }

  // ============================================
  // FUNDING TRACK RECORD
  // ============================================
  if (funding.length > 0) {
    sections.push(`
## FUNDING TRACK RECORD
${funding.map((round, index) => `
### Funding Round ${index + 1}
- **Round Type:** ${round.name || round.type || 'N/A'}
- **Amount:** ${round.targetAmount ? formatCurrency(round.targetAmount) : 'N/A'}
- **Status:** ${round.status || 'N/A'}
- **Date:** ${round.actualCloseDate || round.targetCloseDate || 'N/A'}
- **Investors:** ${round.commitments?.map((c: any) => c.investorName || c.investor).join(', ') || 'N/A'}
- **Valuation:** ${round.postMoneyValuation ? formatCurrency(round.postMoneyValuation) : 'N/A'}
- **Equity Offered:** ${round.equityOffered ? `${round.equityOffered}%` : 'N/A'}
`).join('\n')}
`);
  }

  // ============================================
  // PRESENTATIONS & PITCHES
  // ============================================
  if (presentations.length > 0) {
    sections.push(`
## PRESENTATIONS & PITCHES
${presentations.map((pres, index) => `
### Presentation ${index + 1}
- **Title:** ${pres.title || 'N/A'}
- **Type:** ${pres.type || 'N/A'}
- **Date:** ${pres.createdAt ? new Date(pres.createdAt).toLocaleDateString() : 'N/A'}
- **Target Audience:** ${pres.targetAudience || 'N/A'}
- **Key Message:** ${pres.keyMessage || 'N/A'}
- **Tone:** ${pres.tone || 'N/A'}
- **Number of Slides:** ${pres.numberOfSlides || pres.slides?.length || 'N/A'}
`).join('\n')}
`);
  }

  // ============================================
  // PROFESSIONAL EXPERIENCE (MANUAL ENTRY)
  // ============================================
  if (experience.length > 0) {
    sections.push(`
## PROFESSIONAL EXPERIENCE
${experience.map((exp, index) => `
### Experience ${index + 1}
- **Company:** ${exp.company || 'N/A'}
- **Role/Position:** ${exp.role || 'N/A'}
- **Employment Type:** ${exp.employmentType || 'N/A'}
- **Industry:** ${exp.industry || 'N/A'}
- **Location:** ${exp.location || 'N/A'}
- **Period:** ${exp.startDate || 'N/A'} - ${exp.isCurrent ? 'Present' : exp.endDate || 'N/A'}
- **Currently Working:** ${exp.isCurrent ? 'Yes' : 'No'}
- **Description:** ${exp.description || 'N/A'}
- **Key Achievements:** ${exp.achievements?.join(', ') || 'N/A'}
- **Skills Used:** ${exp.skills?.join(', ') || 'N/A'}
- **Responsibilities:** ${exp.responsibilities?.join(', ') || 'N/A'}
`).join('\n')}
`);
  }

  // ============================================
  // EDUCATION (MANUAL ENTRY)
  // The output schema below asks the model for an "education" array, so without
  // this section it had no source data to build it from.
  // ============================================
  if (education && education.length > 0) {
    sections.push(`
## EDUCATION
${education.map((edu, index) => `
### Education ${index + 1}
- **Institution:** ${edu.institution || 'N/A'}
- **Degree:** ${edu.degree || 'N/A'}
- **Field of Study:** ${edu.field || 'N/A'}
- **Period:** ${edu.startYear || 'N/A'} - ${edu.isCurrent ? 'Present' : edu.endYear || 'N/A'}
- **Grade:** ${edu.grade || 'N/A'}
- **Description:** ${edu.description || 'N/A'}
`).join('\n')}
`);
  }

  // ============================================
  // PROJECTS/PRODUCTS
  // ============================================
  if (projects.length > 0) {
    sections.push(`
## PROJECTS/PRODUCTS
${projects.map((project, index) => `
### Project ${index + 1}
- **Name:** ${project.name || 'N/A'}
- **Description:** ${project.description || 'N/A'}
- **Role:** ${project.role || 'N/A'}
- **Period:** ${project.startDate || 'N/A'} - ${project.isCurrent ? 'Present' : project.endDate || 'N/A'}
- **Status:** ${project.isCurrent ? 'Ongoing' : 'Completed'}
- **Outcomes/Impact:** ${project.outcomes?.join(', ') || 'N/A'}
- **Technologies:** ${project.technologies?.join(', ') || 'N/A'}
- **Team Size:** ${project.teamSize || 'N/A'}
- **Budget:** ${project.budget || 'N/A'}
- **Business Impact:** ${project.businessImpact || 'N/A'}
- **Source:** ${project.source === 'imported' ? 'Imported from Products' : 'Manual Entry'}
`).join('\n')}
`);
  }

  // ============================================
  // MAIN PROMPT
  // ============================================
  return `You are an expert resume writer creating a concise, professional CV for a founder/executive.

Generate a CLEAN, PRACTICAL resume in JSON format. The CV should be:
- CONCISE and SCANNABLE (not verbose or narrative)
- Achievement-focused with quantified results
- Formatted for quick reading by recruiters/investors
- Similar to a modern tech resume (clean, simple, factual)
- Professional but engaging

${sections.join('\n')}

---

## REQUIRED OUTPUT FORMAT (JSON)

Return ONLY valid JSON with this exact structure. Do not include any text before or after the JSON:

{
  "personalInfo": {
    "name": "string",
    "designation": "string",
    "bio": "string (1-2 short sentences max - like a LinkedIn headline)",
    "email": "string",
    "phone": "string",
    "linkedin": "string",
    "otherSocials": { "platform": "url" }
  },
  "executiveSummary": "string (3-4 CONCISE paragraphs: 1st paragraph = who they are + biggest achievement with metric, 2nd paragraph = current role + scope + impact, 3rd paragraph = key expertise areas + unique value, 4th paragraph = notable recognition/funding if applicable. Each paragraph 2-3 sentences max. No fluff.)",
  "experience": [
    {
      "id": "string (uuid)",
      "company": "string",
      "role": "string",
      "employmentType": "full-time|part-time|contract|freelance|internship|co-founder",
      "industry": "string",
      "location": "string",
      "startDate": "string (YYYY-MM)",
      "endDate": "string (YYYY-MM) or null if current",
      "isCurrent": boolean,
      "description": "string (1 short sentence max, or omit)",
      "achievements": ["string (3-5 BULLET POINTS max, each 1 line, action verb + metric/result)"],
      "skills": ["string (3-5 most relevant skills for this role only)"],
      "responsibilities": []
    }
  ],
  "projects": [
    {
      "id": "string (uuid)",
      "name": "string",
      "description": "string (1-2 sentences max: what + tech stack)",
      "role": "string",
      "startDate": "string (YYYY-MM)",
      "endDate": "string (YYYY-MM) or null",
      "isCurrent": boolean,
      "outcomes": ["string (2-3 bullets max: key results, metrics achieved)"],
      "technologies": ["string"],
      "teamSize": number,
      "budget": "string",
      "businessImpact": "string (omit or 1 sentence)",
      "source": "imported|manual"
    }
  ],
  "skills": ["string (8-12 RELEVANT skills max, organized by category: Technical, Business, Leadership, Soft Skills)"],
  "achievements": ["string (3-5 MAJOR achievements max, 1 line each with metric)"],
  "education": [
    {
      "institution": "string",
      "degree": "string",
      "year": "string",
      "field": "string"
    }
  ],
  "certifications": [
    {
      "name": "string",
      "issuer": "string",
      "year": "string"
    }
  ],
  "mediaPresence": {
    "interviews": [
      {
        "id": "string",
        "type": "podcast|tv|media-interview|panel-discussion",
        "title": "string",
        "platform": "string",
        "date": "string",
        "description": "string (omit or 1 line)",
        "highlights": []
      }
    ],
    "speaking": [
      {
        "id": "string",
        "title": "string",
        "event": "string",
        "date": "string",
        "type": "keynote|conference|workshop|guest-lecture|panel",
        "audience": "string",
        "description": "string (omit)",
        "recordingUrl": "string"
      }
    ]
  },
  "fundingTrackRecord": [
    {
      "id": "string",
      "roundType": "string",
      "amount": "string",
      "date": "string",
      "investors": ["string (1-3 key investors)"],
      "milestone": "string (omit)"
    }
  ],
  "presentations": [
    {
      "id": "string",
      "title": "string",
      "type": "string",
      "date": "string",
      "audience": "string",
      "description": "string (omit)",
      "link": "string"
    }
  ]
}

## CRITICAL FORMATTING RULES

1. **Executive Summary** (3-4 concise paragraphs, 2-3 sentences each):
   Paragraph 1 - Identity & Achievement:
   - Who they are + years of experience + domain expertise
   - Biggest quantified achievement (metrics: $, users, growth %)

   Paragraph 2 - Current Role & Scope:
   - Current position + company + industry
   - Team size + budget/revenue responsibility
   - Key impact in current role (1-2 metrics)

   Paragraph 3 - Expertise & Value:
   - 3-4 key expertise areas (technical + business)
   - Unique value proposition
   - Industries/markets they specialize in

   Paragraph 4 - Recognition (if applicable):
   - Notable speaking, publications, or media
   - Funding raised (if founder)
   - Awards or recognition

   Example:
   "Full-stack developer with 5+ years building scalable web applications. Led development of e-commerce platform serving 50K+ monthly users, improving conversion by 35%.

   Currently Senior Developer at TechCorp, managing a team of 8 and overseeing $2M+ annual project budget. Reduced infrastructure costs by 40% through AWS optimization.

   Expertise in React, Node.js, and cloud architecture. Specialized in building high-performance applications for fintech and e-commerce industries. Known for shipping production-ready code 2x faster than industry average.

   Featured speaker at ReactConf 2024. Previously co-founded a SaaS startup that raised $500K seed funding."

2. **Experience** (CONCISE BULLETS):
   - Each role: Company, Title, Dates (one line)
   - Dates format: "Jan 2020 - Present" or "Jan 2020 - Dec 2022"
   - If isCurrent=true, endDate should be null and dates should show "Present"
   - 3-5 bullets max per role
   - Each bullet: Action verb + Result/Metric (one line)
   - Example: "Built and maintained 10+ landing pages using React, improving load times by 40%"
   - NO paragraphs, NO long descriptions
   - NO "responsible for" statements

3. **Projects** (SCANNABLE):
   - Name + Tech Stack (one line)
   - 1-2 sentence description max
   - 2-3 bullet outcomes with metrics
   - Example: "E-Commerce Platform - React, Node.js, MongoDB
     Built responsive shopping platform for 10K+ monthly users
     Implemented payment integration reducing checkout time 30%"

4. **Skills** (ORGANIZED):
   - Group by category: Technical, Business, Leadership
   - 8-12 skills total (not 20)
   - List most relevant first
   - NO generic skills like "Problem Solving" without context

5. **Achievements** (TOP 3-5):
   - One line per achievement
   - Must include metric (number, %, $)
   - Example: "Increased user engagement by 45% through UX improvements"
   - NO vague statements

6. **General Rules**:
   - Remove ALL filler words
   - Remove ALL theoretical explanations
   - Remove ALL vague statements without metrics
   - Prefer numbers over adjectives
   - Prefer action verbs over passive voice
   - Each section should be scannable in < 10 seconds
   - For current roles: ALWAYS show "Present" in dates, set endDate to null, set isCurrent to true

Return ONLY the JSON object, no additional text, no markdown code blocks, no explanation.`;
}

/**
 * Format currency values
 */
function formatCurrency(amount: number): string {
  if (amount >= 1000000) {
    return `$${(amount / 1000000).toFixed(1)}M`;
  } else if (amount >= 1000) {
    return `$${(amount / 1000).toFixed(0)}K`;
  }
  return `$${amount.toLocaleString()}`;
}