import { PhilosophyImpact, ConventionSet } from './types';

/**
 * Layer 1 Finance: Billing Conventions
 * 
 * Philosophy: Automate billing to eliminate administrative burden and ensure
 * equitable access to education regardless of payment timing.
 * 
 * Impact: 12 hours/week saved in billing operations
 */

// Automated billing rules for different fee types
export const BILLING_AUTOMATION_RULES = {
  TUITION: {
    name: 'Tuition Billing Automation',
    schedule: {
      frequency: 'monthly',
      dayOfMonth: 1,
      gracePeriod: 10,
      reminderSchedule: [-7, -3, 0, 3, 7] // Days relative to due date
    },
    paymentOptions: {
      full: { discount: 0.02 },
      semester: { discount: 0.01 },
      monthly: { discount: 0 },
      weekly: { enabled: true, minIncomeQualification: true }
    },
    philosophyMetrics: {
      'payment_flexibility.options': 4,
      'financial_stress.reduced': true,
      'access_barriers.removed': 0.95
    }
  },
  
  ACTIVITY_FEES: {
    name: 'Activity Fee Management',
    schedule: {
      timing: 'at_registration',
      bundleOptions: true,
      familyDiscounts: {
        secondChild: 0.25,
        thirdChild: 0.50,
        additionalChildren: 0.75
      }
    },
    waiverRules: {
      automaticQualification: ['free_lunch', 'reduced_lunch'],
      discretionaryFund: 0.10, // 10% of fees for hardship cases
      anonymousApplication: true
    },
    philosophyMetrics: {
      'activity_access.universal': true,
      'financial_barriers.eliminated': 0.98,
      'family_burden.minimized': true
    }
  },
  
  MEAL_PLANS: {
    name: 'Automated Meal Plan Billing',
    schedule: {
      frequency: 'monthly',
      autoReload: {
        enabled: true,
        threshold: 5.00,
        reloadAmount: 50.00
      }
    },
    subsidyIntegration: {
      freeAndReduced: 'automatic',
      noStigma: true,
      universalBreakfast: true
    },
    philosophyMetrics: {
      'meal_access.guaranteed': 1.0,
      'stigma.eliminated': true,
      'nutrition_security.score': 0.95
    }
  }
};

// Payment processing optimization
export class PaymentProcessor {
  // Intelligent payment routing
  static routePayment(payment: PaymentDetails): ProcessingResult {
    const { amount, method, payerProfile } = payment;
    
    // Choose lowest-cost processor while maintaining reliability
    const processors = this.getAvailableProcessors(method);
    const optimal = processors.reduce((best, current) => {
      const currentCost = this.calculateProcessingCost(amount, current);
      const bestCost = this.calculateProcessingCost(amount, best);
      
      // Factor in reliability and parent experience
      const currentScore = currentCost * (1 - current.reliability * 0.2);
      const bestScore = bestCost * (1 - best.reliability * 0.2);
      
      return currentScore < bestScore ? current : best;
    });
    
    // Apply appropriate payment plan if needed
    if (payerProfile.qualifiesForPlan) {
      return this.setupPaymentPlan(payment, optimal);
    }
    
    return {
      processor: optimal.name,
      fee: this.calculateProcessingCost(amount, optimal),
      estimatedTime: optimal.processingTime,
      confirmationMethod: optimal.confirmation || 'email'
    };
  }
  
  private static getAvailableProcessors(method: string): Processor[] {
    const processors: Record<string, Processor[]> = {
      'credit_card': [
        { name: 'Stripe', rate: 0.029, fixed: 0.30, reliability: 0.99, processingTime: 'instant', confirmation: 'email' },
        { name: 'Square', rate: 0.0275, fixed: 0.30, reliability: 0.98, processingTime: 'instant', confirmation: 'email' },
        { name: 'PayPal', rate: 0.0349, fixed: 0.49, reliability: 0.97, processingTime: '1-2 min', confirmation: 'email' }
      ],
      'ach': [
        { name: 'Plaid', rate: 0.008, fixed: 0, reliability: 0.99, processingTime: '1-2 days', confirmation: 'email' },
        { name: 'Stripe ACH', rate: 0.008, fixed: 0, reliability: 0.99, processingTime: '2-3 days', confirmation: 'email' }
      ],
      'check': [
        { name: 'Check21', rate: 0, fixed: 0.50, reliability: 0.95, processingTime: '3-5 days', confirmation: 'mail' }
      ]
    };
    
    return processors[method] || processors['credit_card'];
  }
  
  private static calculateProcessingCost(amount: number, processor: Processor): number {
    return amount * processor.rate + processor.fixed;
  }
  
  private static setupPaymentPlan(
    payment: PaymentDetails, 
    processor: Processor
  ): ProcessingResult {
    const installments = Math.ceil(payment.amount / 100); // Max $100/month
    
    return {
      processor: processor.name,
      fee: 0, // No fees for payment plans
      estimatedTime: 'recurring',
      confirmationMethod: 'email',
      plan: {
        installments,
        amount: payment.amount / installments,
        frequency: 'monthly',
        autoDebit: true
      }
    };
  }
}

// Fee structure optimization
export class FeeStructureOptimizer {
  // Analyze and optimize fee structures for equity
  static optimizeFeeStructure(
    currentFees: FeeStructure[],
    demographics: SchoolDemographics
  ): OptimizedFeeStructure {
    const { medianIncome, freeReducedLunchRate, communityNeeds } = demographics;
    
    // Calculate affordable base rates
    const affordableMonthlyRate = medianIncome * 0.02; // 2% of income max
    
    const optimized = currentFees.map(fee => {
      // Adjust based on necessity level
      const necessityMultiplier = this.getNecessityMultiplier(fee.category);
      const adjustedAmount = Math.min(
        fee.amount,
        affordableMonthlyRate * necessityMultiplier
      );
      
      return {
        ...fee,
        originalAmount: fee.amount,
        adjustedAmount,
        waiverThreshold: medianIncome * 0.5,
        paymentPlans: this.generatePaymentOptions(adjustedAmount),
        subsidyEligibility: this.calculateSubsidyEligibility(fee, demographics)
      };
    });
    
    return {
      fees: optimized,
      projectedRevenue: this.calculateProjectedRevenue(optimized, demographics),
      equityScore: this.calculateEquityScore(optimized, demographics),
      recommendations: this.generateRecommendations(optimized, demographics)
    };
  }
  
  private static getNecessityMultiplier(category: string): number {
    const multipliers: Record<string, number> = {
      'core_education': 0,      // Should be free
      'meals': 0.5,             // Heavily subsidized
      'transportation': 0.5,
      'technology': 0.7,
      'activities': 1.0,        // Full cost recovery OK
      'premium_services': 1.5   // Can subsidize other areas
    };
    return multipliers[category] || 1.0;
  }
  
  private static generatePaymentOptions(amount: number): PaymentOption[] {
    return [
      { 
        name: 'Annual',
        amount: amount * 10,  // 2 months free
        savings: amount * 2
      },
      {
        name: 'Semester',
        amount: amount * 5.5, // 0.5 months free
        savings: amount * 0.5
      },
      {
        name: 'Monthly',
        amount: amount,
        savings: 0
      },
      {
        name: 'Weekly',
        amount: amount / 4,
        savings: 0,
        qualification: 'income-based'
      }
    ];
  }
  
  private static calculateSubsidyEligibility(
    fee: FeeStructure,
    demographics: SchoolDemographics
  ): number {
    // Higher subsidy for essential services
    const baseSubsidy = fee.category === 'core_education' ? 1.0 :
                       fee.category === 'meals' ? 0.8 :
                       fee.category === 'transportation' ? 0.7 : 0.5;
    
    // Adjust based on community need
    return Math.min(1.0, baseSubsidy + demographics.freeReducedLunchRate * 0.2);
  }
  
  private static calculateEquityScore(
    fees: any[],
    demographics: SchoolDemographics
  ): number {
    // Score based on affordability and access
    let score = 1.0;
    
    // Deduct for unaffordable essential services
    fees.forEach(fee => {
      if (fee.category === 'core_education' && fee.adjustedAmount > 0) score -= 0.2;
      if (fee.adjustedAmount > demographics.medianIncome * 0.03) score -= 0.1;
    });
    
    return Math.max(0, score);
  }
  
  private static calculateProjectedRevenue(
    fees: any[],
    demographics: SchoolDemographics
  ): number {
    return fees.reduce((total, fee) => {
      const paymentRate = 1 - (demographics.freeReducedLunchRate * fee.subsidyEligibility);
      return total + (fee.adjustedAmount * demographics.enrollment * paymentRate);
    }, 0);
  }
  
  private static generateRecommendations(
    fees: any[],
    demographics: SchoolDemographics
  ): string[] {
    const recommendations = [];
    
    if (demographics.freeReducedLunchRate > 0.5) {
      recommendations.push('Consider universal free programs for essential services');
    }
    
    if (fees.some(f => f.adjustedAmount < f.originalAmount * 0.7)) {
      recommendations.push('Seek additional funding sources to maintain programs');
    }
    
    recommendations.push('Implement anonymous fee waiver application system');
    recommendations.push('Partner with community organizations for sponsorships');
    
    return recommendations;
  }
}

// Automated collection workflows
export class CollectionAutomation {
  // Gentle, respectful collection process
  static createCollectionWorkflow(
    account: Account
  ): CollectionWorkflow {
    const { balance, daysOverdue, paymentHistory, specialCircumstances } = account;
    
    // Never penalize students for parent financial issues
    if (specialCircumstances.includes('hardship')) {
      return {
        actions: ['offer_payment_plan', 'connect_with_counselor'],
        communications: ['supportive_email'],
        restrictions: [],
        timeline: 'flexible'
      };
    }
    
    // Graduated response based on history and amount
    if (daysOverdue < 30) {
      return {
        actions: ['friendly_reminder'],
        communications: ['email', 'text'],
        restrictions: [],
        timeline: 'standard'
      };
    } else if (daysOverdue < 60) {
      return {
        actions: ['payment_plan_offer', 'fee_waiver_information'],
        communications: ['phone_call', 'email'],
        restrictions: ['hold_transcripts'],
        timeline: 'extended'
      };
    } else {
      return {
        actions: ['mandatory_meeting', 'financial_counseling'],
        communications: ['certified_letter', 'phone'],
        restrictions: ['registration_hold'],
        timeline: 'immediate',
        escalation: 'never_to_collection_agency' // Philosophy: education first
      };
    }
  }
}

// Convention set for billing automation
export const billingConventions: ConventionSet = {
  name: 'Billing Automation Conventions',
  tribe: 'finance',
  
  conventions: {
    automationRules: BILLING_AUTOMATION_RULES,
    paymentProcessing: {
      processor: PaymentProcessor,
      optimization: 'cost_and_experience'
    },
    feeStructure: {
      optimizer: FeeStructureOptimizer,
      reviewFrequency: 'annual'
    },
    collections: {
      automation: CollectionAutomation,
      philosophy: 'supportive_not_punitive'
    }
  },
  
  philosophyImpact: {
    'billing_time.saved': '12 hours/week',
    'payment_flexibility.increased': 0.90,
    'financial_barriers.removed': 0.95,
    'family_stress.reduced': 0.80
  } as PhilosophyImpact,
  
  metrics: {
    processingCostReduction: '35%',
    onTimePaymentIncrease: '45%',
    financialAccessibility: '98% of families',
    collectionEfficiency: '92% without external agencies'
  }
};

// Types
interface PaymentDetails {
  amount: number;
  method: string;
  payerProfile: {
    qualifiesForPlan: boolean;
    paymentHistory: string[];
  };
}

interface ProcessingResult {
  processor: string;
  fee: number;
  estimatedTime: string;
  confirmationMethod?: string;
  plan?: {
    installments: number;
    amount: number;
    frequency: string;
    autoDebit: boolean;
  };
}

interface Processor {
  name: string;
  rate: number;
  fixed: number;
  reliability: number;
  processingTime: string;
  confirmation?: string;
}

interface FeeStructure {
  name: string;
  category: string;
  amount: number;
  frequency: string;
  mandatory: boolean;
}

interface SchoolDemographics {
  enrollment: number;
  medianIncome: number;
  freeReducedLunchRate: number;
  communityNeeds: string[];
}

interface OptimizedFeeStructure {
  fees: any[];
  projectedRevenue: number;
  equityScore: number;
  recommendations: string[];
}

interface PaymentOption {
  name: string;
  amount: number;
  savings: number;
  qualification?: string;
}

interface Account {
  balance: number;
  daysOverdue: number;
  paymentHistory: string[];
  specialCircumstances: string[];
}

interface CollectionWorkflow {
  actions: string[];
  communications: string[];
  restrictions: string[];
  timeline: string;
  escalation?: string;
}

export default billingConventions; 