{{ config(materialized='table') }}

-- Staging model: Legacy KS4 data from pre-EES DfE performance tables
-- Covers 2015/16 – 2018/19; EES provides 2023/24 onwards.
-- The tap already maps old column names and strips % suffixes;
-- this model just applies safe_numeric casts and adds NULL placeholders
-- for columns not available in the legacy format.

select
    cast(trim(urn) as integer) as urn,
    cast(trim(year) as integer) as year,

    {{ safe_numeric('total_pupils') }}::integer as total_pupils,
    {{ safe_numeric('total_pupils') }}::integer as eligible_pupils,
    null::numeric                               as prior_attainment_avg,

    -- Attainment 8
    {{ safe_numeric('attainment_8_score') }} as attainment_8_score,

    -- Progress 8
    {{ safe_numeric('progress_8_score') }}    as progress_8_score,
    {{ safe_numeric('progress_8_lower_ci') }} as progress_8_lower_ci,
    {{ safe_numeric('progress_8_upper_ci') }} as progress_8_upper_ci,
    {{ safe_numeric('progress_8_english') }}  as progress_8_english,
    {{ safe_numeric('progress_8_maths') }}    as progress_8_maths,
    {{ safe_numeric('progress_8_ebacc') }}    as progress_8_ebacc,
    {{ safe_numeric('progress_8_open') }}     as progress_8_open,

    -- English & Maths pass rates
    {{ safe_numeric('english_maths_strong_pass_pct') }}   as english_maths_strong_pass_pct,
    {{ safe_numeric('english_maths_standard_pass_pct') }} as english_maths_standard_pass_pct,

    -- EBacc
    {{ safe_numeric('ebacc_entry_pct') }}         as ebacc_entry_pct,
    {{ safe_numeric('ebacc_strong_pass_pct') }}   as ebacc_strong_pass_pct,
    {{ safe_numeric('ebacc_standard_pass_pct') }} as ebacc_standard_pass_pct,
    null::numeric                                 as ebacc_avg_score,

    -- GCSE grade 9-1 (not published in legacy format)
    null::numeric as gcse_grade_91_pct,

    -- SEN
    null::numeric                           as sen_pct,
    {{ safe_numeric('sen_ehcp_pct') }}      as sen_ehcp_pct,
    {{ safe_numeric('sen_support_pct') }}   as sen_support_pct,

    -- Progress 8 banding & disadvantage gaps (not published in legacy format)
    null::text    as progress_8_banding,
    null::numeric as attainment_8_disadvantage_gap,
    null::numeric as progress_8_disadvantage_gap

from {{ source('raw', 'legacy_ks4') }}
where urn is not null
  and urn ~ '^[0-9]+$'
