/**
 * Shared Proposal Document Builder
 *
 * Standardized document builder used across:
 * - Production proposal agent (document.ts)
 * - Render PDF diagnostic (render-pdf.ts)
 * - PDF Sandbox (page.tsx)
 *
 * Changes to the page structure here propagate to all consumers automatically.
 *
 * Page Structure:
 * 1. Cover page
 * 2. Executive Summary (with paragraph support)
 * 3. Automation pages (one per automation)
 * 4. Summary + Investment (combined)
 * 5. Acceptance (signature page)
 */

import type { PDFDocument, Page } from '../types'
import { coverSection } from './cover'
import { summarySection } from './summary'
import { automationSection } from './automation'
import { summaryInvestmentSection } from './summary-investment'
import { acceptanceSection } from './acceptance'
import type { AutomationConfig } from './types'

// =============================================================================
// Types
// =============================================================================

/**
 * Standardized proposal document configuration
 *
 * All fields required for building a complete proposal PDF.
 * Used by production, diagnostic, and sandbox.
 */
export interface ProposalDocumentConfig {
  // Cover page fields
  /** Company name (appears on cover and acceptance) */
  company: string
  /** Contact name (appears on cover and acceptance) */
  contact: string
  /** Business vertical (e.g., "Marketing & Creative Agency") */
  vertical: string
  /** Solutions summary (e.g., "Client reporting - Content workflows") */
  solutions: string
  /** Logo as base64 data URL (optional) */
  logoSrc?: string

  // Executive summary
  /** Executive summary text - supports paragraph breaks via \n\n */
  executiveSummary: string

  // Automations (each becomes a detail page)
  /** Automation configurations - each generates one page */
  automations: AutomationConfig[]

  // Acceptance page
  /** Service tier for acceptance page */
  tier: 'tier1' | 'tier2' | 'tier3' | 'custom'
  /** Initial fee amount in dollars (one-time implementation fee) */
  initialFee: number
  /** Monthly fee amount in dollars (optional, for ongoing support) */
  monthlyFee?: number

  // Document metadata
  /** Name of the service provider issuing the proposal (used in acceptance text and document metadata) */
  providerName: string
}

// =============================================================================
// Builder
// =============================================================================

/**
 * Build a standardized proposal PDF document
 *
 * Creates the standard 6+ page proposal structure:
 * 1. Cover page with company branding
 * 2. Executive Summary with key metrics
 * 3-N. Automation detail pages (one per automation)
 * N+1. Summary table + Investment (combined)
 * N+2. Acceptance page with signature fields
 *
 * @param config - Proposal document configuration
 * @returns PDFDocument ready for rendering
 *
 * @example
 * ```typescript
 * import { buildProposalDocument } from '@repo/core/pdf/sections'
 *
 * const document = buildProposalDocument({
 *   company: 'Acme Corp',
 *   contact: 'John Smith',
 *   vertical: 'Marketing Agency',
 *   solutions: 'Reporting - Invoicing',
 *   executiveSummary: 'Based on our discovery call...',
 *   automations: [
 *     { title: 'Client Reporting', hoursPerWeek: 12, annualSavings: 31200, ... }
 *   ],
 *   tier: 'tier2',
 *   initialFee: 5000,
 *   monthlyFee: 2500  // optional
 * })
 * ```
 */
export function buildProposalDocument(config: ProposalDocumentConfig): PDFDocument {
  const {
    company,
    contact,
    vertical,
    solutions,
    logoSrc,
    executiveSummary,
    automations,
    tier,
    initialFee,
    monthlyFee,
    providerName
  } = config

  // Calculate totals for metrics
  const totalSavings = automations.reduce((sum, a) => sum + a.annualSavings, 0)

  // Build page array
  const pages: Page[] = [
    // Page 1: Cover
    coverSection({
      company,
      contact,
      vertical,
      solutions,
      logoSrc
    }),

    // Page 2: Executive Summary
    summarySection({
      totalSavings,
      automationCount: automations.length,
      description: executiveSummary
    }),

    // Pages 3-N: Automation details (one per automation)
    ...automations.map((automation) => automationSection(automation)),

    // Page N+1: Combined Summary Table + Investment
    summaryInvestmentSection({
      automations: automations.map((a) => ({
        title: a.title,
        hoursPerWeek: a.hoursPerWeek,
        annualSavings: a.annualSavings
      })),
      initialFee,
      monthlyFee
    }),

    // Page N+2: Acceptance (signature fields)
    acceptanceSection({
      companyName: company,
      contactName: contact,
      tier,
      initialFee,
      monthlyFee,
      providerName
    })
  ]

  return {
    pages,
    metadata: {
      title: `Proposal for ${company}`,
      author: providerName
    }
  }
}

// =============================================================================
// Helper for generating executive summary text
// =============================================================================

/**
 * Generate standard 3-paragraph executive summary
 *
 * Creates consistent narrative structure:
 * - Paragraph 1: Problem statement with cost impact
 * - Paragraph 2: Solution overview with human oversight emphasis
 * - Paragraph 3: Projected ROI and implementation timeline
 *
 * @param config - Summary generation parameters
 * @returns Executive summary with paragraph breaks (\n\n)
 */
export function generateExecutiveSummary(config: {
  contact: string
  company: string
  totalSavings: number
  totalHoursPerWeek: number
  automationCount: number
}): string {
  const { contact, company, totalSavings, totalHoursPerWeek, automationCount } = config

  return `${contact}, your team at ${company} is caught in a cycle of inefficiency that's quietly draining $${totalSavings.toLocaleString()} annually from your bottom line. These aren't just administrative headaches - they're opportunities slipping through the cracks, relationships strained by delays, and time wasted on tasks that could run themselves.

This proposal outlines ${automationCount} targeted automations designed specifically for ${company}'s workflow. Each solution maintains human oversight at critical decision points while eliminating the repetitive tasks consuming your team's time. We're not replacing your people - we're freeing them to focus on what they do best.

The projected annual savings of $${totalSavings.toLocaleString()} represents 70% of the cost you're currently losing to manual processes. More importantly, reclaiming ${totalHoursPerWeek} hours per week means your team can take on more work without burning out. The automations outlined here can be implemented within 2-3 weeks of approval.`
}
