input($exposure_layer, name: 'exposure') as exposures_input
 -> select({exposure}) as exposures
 -> join(on: true) as exposures_join_hazards
 -> select({*, sample_one(geometry: exposure, coverage: hazard) as hazard}) as "sample_hazard_layer"
 -> join(on: true) as exposures_join_areas
 -> select({*, sample_one(geometry: exposure, coverage: area, buffer-distance: 1000) as area})
 -> select({*, DamageState: map(hazard, hv -> Building_Damage_State(exposure, hv)) })
 -> select({*, Probability: map(hazard, hv -> Samoa_Building_Fragility(exposure, hv)) })
 -> select({*}) as event_impact_table

input(value: $hazard_layer, name: 'hazard') as hazards_input
 -> select({hazard as hazard}) as hazards
 -> exposures_join_hazards.rhs

input(relation: $area_layer, name: 'area') as areas_input
 -> group({to_coverage(area) as area}) as areas
 -> exposures_join_areas.rhs

event_impact_table
 -> select({*}) as "report_event-impact"
 -> group(by: {area.Region as Region}, select: {Region, count(hazard) as Number_Exposed, count(exposure) as Total_buildings, bucket(pick: b -> b = DamageState, select: {count(*)}, buckets: {None: '0: Not damaged', Light: '1: Light', Minor: '2: Minor', Moderate: '3: Moderate', Severe: '4: Severe', Collapse: '5: Collapse'}) as Damage})
 -> sort([Region], direction: ['ASC'])
 -> save(name: 'summary', format: 'csv') as save_summary
 
 event_impact_table
 -> select({ exposure.*, hazard, DamageState, area.Region, Probability })
 -> save(name: 'event-impact', format: 'geopackage') as save_event_impact

 event_impact_table
  -> group(by: {area as Region}, select: {Region, count(hazard) as Number_Exposed, count(exposure) as Total_buildings, bucket(pick: b -> b = DamageState, select: {count(*)}, buckets: {None: '0: Not damaged', Light: '1: Light', Minor: '2: Minor', Moderate: '3: Moderate', Severe: '4: Severe', Collapse: '5: Collapse'}) as Damage})
   # make things slightly easier to access from the pandas dataframe
  -> select({ *, Damage.*, Damage.Collapse.count as Collapsed })  as summary
  -> save(name: 'regional-impact', format: 'geojson') as save_regional_impact

summary -> python('functions/pdf.py')