/**
 * Vertical Farming Types for LocalGreenChain
 * Complete vertical farm management, automation, and integration
 */

// Vertical Farm facility
export interface VerticalFarm {
  id: string;
  name: string;
  ownerId: string;

  // Location
  location: {
    latitude: number;
    longitude: number;
    address: string;
    city: string;
    country: string;
    timezone: string;
  };

  // Facility specs
  specs: FacilitySpecs;

  // Growing zones
  zones: GrowingZone[];

  // Systems
  environmentalControl: EnvironmentalControlSystem;
  irrigationSystem: IrrigationSystem;
  lightingSystem: LightingSystem;
  nutrientSystem: NutrientDeliverySystem;

  // Automation
  automationLevel: 'manual' | 'semi_automated' | 'fully_automated';
  automationSystems: AutomationSystem[];

  // Status
  status: 'offline' | 'starting' | 'operational' | 'maintenance' | 'emergency';
  operationalSince: string;
  lastMaintenanceDate: string;

  // Performance
  currentCapacityUtilization: number; // 0-100
  averageYieldEfficiency: number; // vs theoretical max
  energyEfficiencyScore: number; // 0-100
}

export interface FacilitySpecs {
  totalAreaSqm: number;
  growingAreaSqm: number;
  numberOfLevels: number;
  ceilingHeightM: number;

  // Capacity
  totalGrowingPositions: number;
  currentActivePlants: number;

  // Infrastructure
  powerCapacityKw: number;
  waterStorageL: number;
  backupPowerHours: number;

  // Certifications
  certifications: ('organic' | 'gap' | 'haccp' | 'iso_22000' | 'local_food_safety')[];

  // Building
  buildingType: 'warehouse' | 'greenhouse' | 'container' | 'purpose_built' | 'retrofit';
  insulation: 'standard' | 'high_efficiency' | 'passive';
}

export interface GrowingZone {
  id: string;
  name: string;
  level: number;

  // Dimensions
  areaSqm: number;
  lengthM: number;
  widthM: number;

  // Growing system
  growingMethod: 'NFT' | 'DWC' | 'ebb_flow' | 'aeroponics' | 'vertical_towers' | 'rack_system';
  plantPositions: number;

  // Current status
  currentCrop: string;
  plantIds: string[];
  plantingDate: string;
  expectedHarvestDate: string;

  // Environment targets
  environmentTargets: ZoneEnvironmentTargets;

  // Current readings
  currentEnvironment: ZoneEnvironmentReadings;

  // Status
  status: 'empty' | 'preparing' | 'planted' | 'growing' | 'harvesting' | 'cleaning';
}

export interface ZoneEnvironmentTargets {
  temperatureC: { min: number; max: number; target: number };
  humidityPercent: { min: number; max: number; target: number };
  co2Ppm: { min: number; max: number; target: number };
  lightPpfd: { min: number; max: number; target: number };
  lightHours: number;
  nutrientEc: { min: number; max: number; target: number };
  nutrientPh: { min: number; max: number; target: number };
  waterTempC: { min: number; max: number; target: number };
}

export interface ZoneEnvironmentReadings {
  timestamp: string;

  // Air
  temperatureC: number;
  humidityPercent: number;
  co2Ppm: number;
  vpd: number; // Vapor Pressure Deficit

  // Light
  ppfd: number;
  dli: number; // Daily Light Integral

  // Water/Nutrients
  waterTempC: number;
  ec: number;
  ph: number;
  dissolvedOxygenPpm: number;

  // Air quality
  airflowMs: number;

  // Status flags
  alerts: EnvironmentAlert[];
}

export interface EnvironmentAlert {
  parameter: string;
  type: 'low' | 'high' | 'critical_low' | 'critical_high' | 'sensor_fault';
  value: number;
  threshold: number;
  timestamp: string;
  acknowledged: boolean;
}

// Environmental Control System
export interface EnvironmentalControlSystem {
  hvacUnits: HVACUnit[];
  co2Injection: CO2System;
  humidification: HumidificationSystem;
  airCirculation: AirCirculationSystem;

  // Control mode
  controlMode: 'manual' | 'scheduled' | 'adaptive' | 'ai_optimized';
}

export interface HVACUnit {
  id: string;
  type: 'cooling' | 'heating' | 'heat_pump';
  capacityKw: number;
  zones: string[];
  status: 'off' | 'running' | 'fault';
  currentPowerKw: number;
  setpointC: number;
}

export interface CO2System {
  type: 'tank' | 'generator' | 'burner';
  capacityKg: number;
  currentLevelKg: number;
  injectionRateKgPerHour: number;
  status: 'off' | 'injecting' | 'maintaining' | 'fault';
}

export interface HumidificationSystem {
  type: 'misting' | 'ultrasonic' | 'evaporative';
  capacityLPerHour: number;
  status: 'off' | 'running' | 'fault';
  currentOutput: number;
}

export interface AirCirculationSystem {
  fans: {
    id: string;
    zone: string;
    type: 'circulation' | 'exhaust' | 'intake';
    speedPercent: number;
    status: 'off' | 'running' | 'fault';
  }[];
}

// Irrigation System
export interface IrrigationSystem {
  type: 'recirculating' | 'drain_to_waste';

  // Tanks
  freshWaterTankL: number;
  freshWaterLevelL: number;
  nutrientTankL: number;
  nutrientLevelL: number;
  wasteTankL: number;
  wasteLevelL: number;

  // Water treatment
  waterTreatment: {
    ro: boolean;
    uv: boolean;
    ozone: boolean;
    filtration: string;
  };

  // Pumps
  pumps: {
    id: string;
    type: 'main' | 'zone' | 'recirculation' | 'drain';
    status: 'off' | 'running' | 'fault';
    flowRateLPerMin: number;
  }[];

  // Schedule
  irrigationSchedule: IrrigationSchedule[];
}

export interface IrrigationSchedule {
  zoneId: string;
  frequencyPerDay: number;
  durationMinutes: number;
  times: string[]; // HH:MM format
}

// Lighting System
export interface LightingSystem {
  type: 'LED' | 'HPS' | 'fluorescent' | 'hybrid';

  // Fixtures
  fixtures: LightFixture[];

  // Schedules
  lightSchedules: LightSchedule[];

  // Energy
  totalWattage: number;
  currentWattage: number;
  efficacyUmolJ: number;
}

export interface LightFixture {
  id: string;
  zoneId: string;
  type: 'LED_full_spectrum' | 'LED_red_blue' | 'LED_tunable' | 'HPS' | 'fluorescent';
  wattage: number;
  ppfdAtCanopy: number;
  spectrum: {
    red: number;
    blue: number;
    green: number;
    farRed: number;
    uv: number;
  };
  dimmingPercent: number;
  status: 'off' | 'on' | 'dimmed' | 'fault';
}

export interface LightSchedule {
  zoneId: string;
  photoperiod: {
    onTime: string; // HH:MM
    offTime: string;
    totalHours: number;
  };
  intensity: {
    dayPpfd: number;
    nightPpfd: number;
    rampMinutes: number;
  };
  spectrum?: {
    vegetative: { red: number; blue: number };
    flowering: { red: number; blue: number };
  };
}

// Nutrient Delivery System
export interface NutrientDeliverySystem {
  mixingMethod: 'manual' | 'semi_auto' | 'fully_auto';

  // Stock solutions
  stockSolutions: StockSolution[];

  // Dosing
  dosingPumps: DosingPump[];

  // Current mix
  currentRecipe: NutrientRecipe;

  // Monitoring
  monitoring: {
    ec: number;
    ph: number;
    lastCalibration: string;
    calibrationDue: string;
  };
}

export interface StockSolution {
  id: string;
  name: string;
  type: 'nutrient_a' | 'nutrient_b' | 'cal_mag' | 'ph_up' | 'ph_down' | 'silica' | 'beneficial';
  concentration: string;
  tankSizeL: number;
  currentLevelL: number;
  reorderThresholdL: number;
}

export interface DosingPump {
  id: string;
  solutionId: string;
  flowRateMlPerMin: number;
  status: 'idle' | 'dosing' | 'fault';
  totalDosedMl: number;
}

export interface NutrientRecipe {
  id: string;
  name: string;
  cropType: string;
  growthStage: 'seedling' | 'vegetative' | 'transition' | 'flowering' | 'fruiting';

  // Targets
  targetEc: number;
  targetPh: number;

  // Ratios
  ratios: {
    n: number;
    p: number;
    k: number;
    ca: number;
    mg: number;
    s: number;
    fe: number;
    mn: number;
    zn: number;
    cu: number;
    b: number;
    mo: number;
  };

  // Dosing
  dosingRatiosMlPerL: { solutionId: string; mlPerL: number }[];
}

// Automation System
export interface AutomationSystem {
  id: string;
  name: string;
  type: 'planting' | 'transplanting' | 'harvesting' | 'packaging' | 'monitoring' | 'cleaning';

  // Hardware
  hardware: {
    type: 'robotic_arm' | 'conveyor' | 'camera' | 'sensor_array' | 'mobile_robot';
    model: string;
    status: 'idle' | 'running' | 'maintenance' | 'fault';
  };

  // Capabilities
  capabilities: string[];
  throughputPerHour: number;

  // Integration
  apiEndpoint?: string;
  integrationStatus: 'connected' | 'disconnected' | 'error';
}

// Growing Recipe
export interface GrowingRecipe {
  id: string;
  name: string;
  cropType: string;
  variety?: string;
  version: string;

  // Stages
  stages: GrowthStage[];

  // Expected outcomes
  expectedDays: number;
  expectedYieldGrams: number;
  expectedYieldPerSqm: number;

  // Requirements
  requirements: {
    positions: number;
    zoneType: string;
    minimumPpfd: number;
    idealTemperatureC: number;
  };

  // Source
  source: 'internal' | 'community' | 'commercial';
  author?: string;
  rating?: number;
  timesUsed: number;
}

export interface GrowthStage {
  name: string;
  daysStart: number;
  daysEnd: number;

  // Environment
  temperature: { day: number; night: number };
  humidity: { day: number; night: number };
  co2Ppm: number;
  lightHours: number;
  lightPpfd: number;

  // Nutrients
  nutrientRecipeId: string;
  targetEc: number;
  targetPh: number;

  // Actions
  actions: StageAction[];
}

export interface StageAction {
  day: number;
  action: 'transplant' | 'thin' | 'train' | 'top' | 'pollinate' | 'harvest_partial';
  description: string;
  automated: boolean;
}

// Crop Batch for tracking
export interface CropBatch {
  id: string;
  farmId: string;
  zoneId: string;

  // Crop info
  cropType: string;
  variety?: string;
  recipeId: string;

  // Planting
  seedBatchId: string;
  plantIds: string[];
  plantCount: number;
  plantingDate: string;
  transplantDate?: string;

  // Progress
  currentStage: string;
  currentDay: number;
  healthScore: number;

  // Expected
  expectedHarvestDate: string;
  expectedYieldKg: number;

  // Actual (after harvest)
  actualHarvestDate?: string;
  actualYieldKg?: number;
  qualityGrade?: string;

  // Status
  status: 'germinating' | 'growing' | 'ready' | 'harvesting' | 'completed' | 'failed';

  // Issues
  issues: BatchIssue[];

  // Environmental log
  environmentLog: {
    timestamp: string;
    readings: ZoneEnvironmentReadings;
  }[];
}

export interface BatchIssue {
  id: string;
  timestamp: string;
  type: 'pest' | 'disease' | 'nutrient' | 'environment' | 'equipment' | 'other';
  severity: 'minor' | 'moderate' | 'severe' | 'critical';
  description: string;
  affectedPlants: number;
  resolution?: string;
  resolvedAt?: string;
}

// Energy and Resource Tracking
export interface ResourceUsage {
  farmId: string;
  periodStart: string;
  periodEnd: string;

  // Energy
  electricityKwh: number;
  electricityCostUsd: number;
  renewablePercent: number;
  peakDemandKw: number;

  // Water
  waterUsageL: number;
  waterCostUsd: number;
  waterRecycledPercent: number;

  // CO2
  co2UsedKg: number;
  co2CostUsd: number;

  // Nutrients
  nutrientsUsedL: number;
  nutrientCostUsd: number;

  // Comparison
  kwhPerKgProduce: number;
  litersPerKgProduce: number;
  costPerKgProduce: number;

  // Benchmarks
  industryBenchmarkKwhPerKg: number;
  industryBenchmarkLitersPerKg: number;
  efficiencyVsBenchmark: number;
}

// Vertical Farm Analytics
export interface FarmAnalytics {
  farmId: string;
  generatedAt: string;
  period: string;

  // Production
  totalYieldKg: number;
  yieldPerSqmPerYear: number;
  cropCyclesCompleted: number;
  averageCyclesDays: number;

  // Quality
  averageQualityScore: number;
  gradeAPercent: number;
  wastagePercent: number;

  // Efficiency
  cropSuccessRate: number;
  spaceUtilization: number;
  laborHoursPerKg: number;

  // Financial
  revenueUsd: number;
  costUsd: number;
  profitMarginPercent: number;
  revenuePerSqm: number;

  // Environmental
  carbonFootprintKgPerKg: number;
  waterUseLPerKg: number;
  energyUseKwhPerKg: number;

  // Top crops
  topCropsByYield: { crop: string; yieldKg: number }[];
  topCropsByRevenue: { crop: string; revenueUsd: number }[];
  topCropsByEfficiency: { crop: string; efficiencyScore: number }[];
}
