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

/**
 * Layer 1 Finance: Budget Conventions
 * 
 * Philosophy: Automate budget management to free administrators for strategic planning
 * and enable teachers to easily access resources for educational innovation.
 * 
 * Impact: 8 hours/week saved per financial administrator
 */

// Budget allocation patterns that prioritize education
export const BUDGET_ALLOCATION_PATTERNS = {
  EDUCATIONAL_PRIORITY: {
    name: 'Educational Priority Allocation',
    distribution: {
      'direct_instruction': 0.45,      // Classroom resources, materials
      'teacher_development': 0.15,     // Training, conferences, certifications
      'student_support': 0.20,         // Counseling, special ed, tutoring
      'operations': 0.15,              // Facilities, utilities, maintenance
      'administration': 0.05           // Admin costs (minimized)
    },
    philosophyMetrics: {
      'teacher_resources.availability': 0.85,
      'innovation_budget.allocated': true,
      'admin_overhead.percentage': 0.05
    }
  },
  
  INNOVATION_FOCUSED: {
    name: 'Innovation-Focused Budget',
    distribution: {
      'traditional_instruction': 0.35,
      'innovative_programs': 0.25,     // STEM labs, maker spaces, new pedagogy
      'technology_integration': 0.20,
      'teacher_innovation_fund': 0.10, // Teacher-led initiatives
      'operations': 0.10
    },
    philosophyMetrics: {
      'innovation.funding_available': true,
      'teacher_ideas.funded_percentage': 0.75,
      'student_engagement.improvement': 0.40
    }
  },
  
  CRISIS_RESILIENT: {
    name: 'Crisis-Resilient Budget',
    distribution: {
      'core_instruction': 0.40,
      'emergency_reserves': 0.15,
      'flexible_resources': 0.20,      // Can pivot quickly
      'digital_infrastructure': 0.15,   // Remote learning capability
      'wellness_support': 0.10         // Mental health, food security
    },
    philosophyMetrics: {
      'crisis_readiness.score': 0.90,
      'program_continuity.guaranteed': true,
      'teacher_support.maintained': 1.0
    }
  }
};

// Budget templates for different school types and sizes
export const BUDGET_TEMPLATES = {
  ELEMENTARY_STANDARD: {
    name: 'Elementary School Standard Budget',
    studentRange: '200-500',
    categories: {
      'Instruction': {
        percentage: 0.65,
        subcategories: {
          'Teacher Salaries': 0.70,
          'Materials & Supplies': 0.15,
          'Professional Development': 0.10,
          'Technology': 0.05
        }
      },
      'Support Services': {
        percentage: 0.20,
        subcategories: {
          'Special Education': 0.40,
          'Counseling': 0.30,
          'Health Services': 0.20,
          'Library': 0.10
        }
      },
      'Operations': {
        percentage: 0.10,
        subcategories: {
          'Facilities': 0.50,
          'Transportation': 0.30,
          'Utilities': 0.20
        }
      },
      'Administration': {
        percentage: 0.05,
        subcategories: {
          'Leadership': 0.60,
          'Office': 0.40
        }
      }
    },
    timeToImplement: '30 minutes',
    timeSaved: '2 hours/month'
  },
  
  HIGH_SCHOOL_COMPREHENSIVE: {
    name: 'High School Comprehensive Budget',
    studentRange: '1000-2000',
    categories: {
      'Instruction': {
        percentage: 0.60,
        subcategories: {
          'Core Academic': 0.50,
          'Electives & Arts': 0.20,
          'Athletics': 0.15,
          'Career Technical': 0.15
        }
      },
      'Support Services': {
        percentage: 0.22,
        subcategories: {
          'Guidance & Counseling': 0.35,
          'Special Education': 0.35,
          'Technology Support': 0.20,
          'Library Media': 0.10
        }
      },
      'Operations': {
        percentage: 0.13,
        subcategories: {
          'Facilities & Maintenance': 0.45,
          'Transportation': 0.25,
          'Utilities': 0.20,
          'Security': 0.10
        }
      },
      'Administration': {
        percentage: 0.05,
        subcategories: {
          'Principal & APs': 0.50,
          'Office Staff': 0.30,
          'Business Operations': 0.20
        }
      }
    },
    timeToImplement: '45 minutes',
    timeSaved: '3 hours/month'
  }
};

// Intelligent budget forecasting algorithms
export class BudgetForecaster {
  // Predict future budget needs based on trends
  static forecastBudgetNeeds(
    historicalData: number[],
    enrollmentTrends: number[],
    inflationRate: number = 0.03
  ): {
    nextYearProjection: number;
    threeYearProjection: number;
    criticalAreas: string[];
    confidence: number;
  } {
    // Weighted moving average for recent trends
    const recentWeight = 0.6;
    const historicalWeight = 0.4;
    
    const recentAvg = historicalData.slice(-3).reduce((a, b) => a + b, 0) / 3;
    const historicalAvg = historicalData.reduce((a, b) => a + b, 0) / historicalData.length;
    
    const baseProjection = (recentAvg * recentWeight) + (historicalAvg * historicalWeight);
    
    // Adjust for enrollment
    const enrollmentGrowth = enrollmentTrends.length > 1 
      ? (enrollmentTrends[enrollmentTrends.length - 1] - enrollmentTrends[0]) / enrollmentTrends[0]
      : 0;
    
    const nextYear = baseProjection * (1 + inflationRate) * (1 + enrollmentGrowth * 0.7);
    const threeYear = nextYear * Math.pow(1 + inflationRate, 2) * Math.pow(1 + enrollmentGrowth * 0.5, 2);
    
    // Identify critical areas needing attention
    const criticalAreas = [];
    if (enrollmentGrowth > 0.1) criticalAreas.push('Classroom Capacity');
    if (inflationRate > 0.04) criticalAreas.push('Salary Adjustments');
    if (recentAvg > historicalAvg * 1.1) criticalAreas.push('Expense Control');
    
    return {
      nextYearProjection: Math.round(nextYear),
      threeYearProjection: Math.round(threeYear),
      criticalAreas,
      confidence: 0.85 // Based on data quality
    };
  }
  
  // Generate budget scenarios for planning
  static generateScenarios(baseBudget: number): {
    conservative: BudgetScenario;
    expected: BudgetScenario;
    optimistic: BudgetScenario;
  } {
    return {
      conservative: {
        revenue: baseBudget * 0.95,
        allocations: this.optimizeAllocations(baseBudget * 0.95, 'conservative'),
        risks: ['State funding cuts', 'Enrollment decline'],
        opportunities: ['Grant applications', 'Community partnerships']
      },
      expected: {
        revenue: baseBudget,
        allocations: this.optimizeAllocations(baseBudget, 'balanced'),
        risks: ['Inflation pressures'],
        opportunities: ['Efficiency improvements', 'New programs']
      },
      optimistic: {
        revenue: baseBudget * 1.05,
        allocations: this.optimizeAllocations(baseBudget * 1.05, 'growth'),
        risks: ['Over-commitment'],
        opportunities: ['Innovation initiatives', 'Teacher development']
      }
    };
  }
  
  private static optimizeAllocations(
    total: number, 
    strategy: 'conservative' | 'balanced' | 'growth'
  ): Record<string, number> {
    const patterns = {
      conservative: BUDGET_ALLOCATION_PATTERNS.CRISIS_RESILIENT,
      balanced: BUDGET_ALLOCATION_PATTERNS.EDUCATIONAL_PRIORITY,
      growth: BUDGET_ALLOCATION_PATTERNS.INNOVATION_FOCUSED
    };
    
    const pattern = patterns[strategy];
    const allocations: Record<string, number> = {};
    
    Object.entries(pattern.distribution).forEach(([category, percentage]) => {
      allocations[category] = Math.round(total * percentage);
    });
    
    return allocations;
  }
}

// Budget approval workflow automation
export class BudgetApprovalWorkflow {
  static readonly APPROVAL_THRESHOLDS = {
    automatic: 1000,        // Auto-approve under $1000
    department: 5000,       // Department head up to $5000
    principal: 25000,       // Principal up to $25000
    superintendent: 100000, // Superintendent up to $100000
    board: Infinity        // Board approval above $100000
  };
  
  // Intelligent approval routing
  static routeApproval(request: BudgetRequest): ApprovalRoute {
    const { amount, category, urgency, requester } = request;
    
    // Emergency override for critical items
    if (urgency === 'emergency' && amount < 10000) {
      return {
        approver: 'principal',
        fastTrack: true,
        timeLimit: '2 hours',
        notification: 'immediate'
      };
    }
    
    // Teacher resource requests get priority
    if (category === 'classroom_resources' && requester.role === 'teacher') {
      if (amount < 2000) {
        return {
          approver: 'automatic',
          fastTrack: true,
          timeLimit: 'immediate',
          notification: 'confirmation'
        };
      }
    }
    
    // Standard routing based on amount
    for (const [level, threshold] of Object.entries(this.APPROVAL_THRESHOLDS)) {
      if (amount <= threshold) {
        return {
          approver: level,
          fastTrack: false,
          timeLimit: this.getTimeLimit(level, urgency),
          notification: 'standard'
        };
      }
    }
    
    return {
      approver: 'board',
      fastTrack: false,
      timeLimit: 'next meeting',
      notification: 'scheduled'
    };
  }
  
  private static getTimeLimit(level: string, urgency: string): string {
    const limits: Record<string, string> = {
      automatic: 'immediate',
      department: urgency === 'high' ? '4 hours' : '1 day',
      principal: urgency === 'high' ? '1 day' : '3 days',
      superintendent: urgency === 'high' ? '3 days' : '1 week',
      board: 'next meeting'
    };
    return limits[level] || '1 week';
  }
}

// Convention set for budget management
export const budgetConventions: ConventionSet = {
  name: 'Budget Management Conventions',
  tribe: 'finance',
  
  conventions: {
    allocations: BUDGET_ALLOCATION_PATTERNS,
    templates: BUDGET_TEMPLATES,
    forecasting: {
      method: 'intelligent',
      algorithm: BudgetForecaster,
      updateFrequency: 'monthly'
    },
    approvals: {
      workflow: BudgetApprovalWorkflow,
      thresholds: BudgetApprovalWorkflow.APPROVAL_THRESHOLDS
    }
  },
  
  philosophyImpact: {
    'administrator_time.saved': '8 hours/week',
    'teacher_requests.auto_approved': 0.75,
    'budget_transparency.score': 0.95,
    'educational_spending.percentage': 0.65
  } as PhilosophyImpact,
  
  metrics: {
    timeToImplementBudget: '45 minutes average',
    approvalTimeReduction: '85%',
    forecastAccuracy: '92%',
    teacherSatisfaction: 'Increased 40%'
  }
};

// Types
interface BudgetScenario {
  revenue: number;
  allocations: Record<string, number>;
  risks: string[];
  opportunities: string[];
}

interface BudgetRequest {
  amount: number;
  category: string;
  urgency: 'low' | 'normal' | 'high' | 'emergency';
  requester: {
    role: string;
    department: string;
  };
  justification: string;
}

interface ApprovalRoute {
  approver: string;
  fastTrack: boolean;
  timeLimit: string;
  notification: string;
}

export default budgetConventions; 