/**
 * TypeScript type definitions for SchoolCompare API
 * Generated from backend/models.py and backend/schemas.py
 */

// ============================================================================
// School Types
// ============================================================================

export interface School {
  id?: number;
  urn: number;
  school_name: string;
  local_authority: string | null;
  local_authority_code: number | null;
  school_type: string | null;
  school_type_code: string | null;
  religious_denomination: string | null;
  age_range: string | null;
  has_sixth_form?: boolean | null;
  nursery_provision?: boolean | null;
  status?: string | null; // GIAS establishment status ("Open" / "Open, but proposed to close")

  // Address
  address1: string | null;
  address2: string | null;
  town: string | null;
  postcode: string | null;
  address?: string; // Computed full address

  // Geocoding
  latitude: number | null;
  longitude: number | null;

  // School context
  total_pupils?: number | null;

  // Latest year metrics (for search/list views)
  rwm_expected_pct?: number | null;
  reading_expected_pct?: number | null;
  writing_expected_pct?: number | null;
  maths_expected_pct?: number | null;
  reading_progress?: number | null;
  writing_progress?: number | null;
  maths_progress?: number | null;

  // Trend indicators (for list views)
  prev_rwm_expected_pct?: number | null;
  trend?: 'up' | 'down' | 'stable';

  // Location search fields
  distance?: number | null;

  // Phase (Primary, Secondary, All-through, etc.)
  phase?: string | null;

  // KS4 card metrics
  attainment_8_score?: number | null;
  english_maths_standard_pass_pct?: number | null;
  prev_attainment_8_score?: number | null;

  // GIAS enrichment fields
  website?: string | null;
  telephone?: string | null;
  headteacher_name?: string | null;
  capacity?: number | null;
  trust_name?: string | null;
  gender?: string | null;
  admissions_policy?: string | null;
  county?: string | null;
  parliamentary_constituency?: string | null;

  // Ofsted (for list view — summary only)
  ofsted_grade?: 1 | 2 | 3 | 4 | null;
  /** Report-card inspection date (Nov 2025+); non-null identifies a report
   * card in the list/map, where the full report_card object isn't available. */
  ofsted_rc_date?: string | null;
  ofsted_date?: string | null;
  ofsted_framework?: string | null;
}

// ============================================================================
// Supplementary Data Types (populated by Kestra data integrator)
// ============================================================================

export interface OfstedInspection {
  framework: 'OEIF' | 'ReportCard' | null;
  inspection_date: string | null;
  /** Start date of the report-card inspection itself (Nov 2025+); null otherwise. */
  rc_inspection_date?: string | null;
  inspection_type: string | null;
  // OEIF fields (old framework, pre-Nov 2025)
  overall_effectiveness: 1 | 2 | 3 | 4 | null;
  quality_of_education: number | null;
  behaviour_attitudes: number | null;
  personal_development: number | null;
  /** Sixth-form judgement where applicable; sentinel 9 = not applicable. */
  sixth_form_provision?: number | null;
  leadership_management: number | null;
  early_years_provision: number | null;
  previous_overall: number | null;
  // Report Card fields (new framework, from Nov 2025)
  // 1=Exceptional 2=Strong 3=Expected standard 4=Needs attention 5=Urgent improvement
  rc_safeguarding_met: boolean | null;
  rc_inclusion: number | null;
  rc_curriculum_teaching: number | null;
  rc_achievement: number | null;
  rc_attendance_behaviour: number | null;
  rc_personal_development: number | null;
  rc_leadership_governance: number | null;
  rc_early_years: number | null;
  rc_sixth_form: number | null;
  /** Where the effective overall grade came from: a graded (Section 5)
   * inspection, or carried forward from an ungraded (Section 8) outcome. */
  grade_source?: 'graded' | 'ungraded_carried_forward' | null;
  /** Renewed-framework (Nov 2025) area judgements, coded + labelled by the
   * backend from the live-sampled Ofsted vocabulary. Empty when the school
   * has no report-card inspection. Safeguarding is never included here. */
  report_card?: Record<string, ReportCardEntry>;
  /** The school's page on ofsted.gov.uk (never a deep report link). */
  ofsted_page_url?: string;
  report_url?: string | null;
}

export interface ReportCardEntry {
  code: number;
  label: string;
}

export interface SchoolCensus {
  year: number;
  total_pupils: number | null;
  female_pupils: number | null;
  male_pupils: number | null;
  fsm_pct: number | null;
  eal_pct: number | null;
  ethnicity_white_pct?: number | null;
  ethnicity_asian_pct?: number | null;
  ethnicity_black_pct?: number | null;
  ethnicity_mixed_pct?: number | null;
  ethnicity_other_pct?: number | null;
}

export interface SchoolAdmissions {
  year: number;
  school_phase?: string | null;
  /** Number of places the school offered in this admissions round (not PAN — EES doesn't expose PAN). */
  places_offered: number | null;
  total_applications: number | null;
  first_preference_applications?: number | null;
  first_preference_offers?: number | null;
  /** Of families who listed this school as 1st preference, the % that received an offer (0–100). */
  first_preference_offer_pct: number | null;
  /** 1st-preference applications per place offered (>1 means oversubscribed). */
  oversubscription_ratio?: number | null;
  oversubscribed: boolean | null;
  total_offers?: number | null;
  second_preference_offers?: number | null;
  third_preference_offers?: number | null;
  /** Applications naming this school from families in another LA, and offers to them. */
  cross_la_applications?: number | null;
  cross_la_offers?: number | null;
}


export interface SchoolDeprivation {
  lsoa_code: string | null;
  idaci_score: number | null;
  idaci_decile: number | null;
}

export interface SchoolFinance {
  year: number;
  per_pupil_spend: number | null;
  staff_cost_pct: number | null;
  teacher_cost_pct: number | null;
  support_staff_cost_pct: number | null;
  premises_cost_pct: number | null;
}

// ============================================================================
// School Result Types
// ============================================================================

export interface SchoolResult {
  id?: number;
  school_id: number;
  year: number;

  // Progress confidence intervals + writing working-towards (published for
  // years with progress measures, i.e. up to 2022/23)
  reading_progress_lower_ci?: number | null;
  reading_progress_upper_ci?: number | null;
  writing_progress_lower_ci?: number | null;
  writing_progress_upper_ci?: number | null;
  writing_working_towards_pct?: number | null;
  maths_progress_lower_ci?: number | null;
  maths_progress_upper_ci?: number | null;

  // KS4 banding and disadvantage gaps
  /** DfE's own plain-English Progress 8 label, e.g. "Well above average". */
  progress_8_banding?: string | null;
  attainment_8_disadvantage_gap?: number | null;
  progress_8_disadvantage_gap?: number | null;

  // Pupil numbers
  total_pupils: number | null;
  eligible_pupils: number | null;

  // Core KS2 metrics - Expected Standard
  rwm_expected_pct: number | null;
  reading_expected_pct: number | null;
  writing_expected_pct: number | null;
  maths_expected_pct: number | null;
  gps_expected_pct: number | null;
  science_expected_pct: number | null;

  // Higher Standard
  rwm_high_pct: number | null;
  reading_high_pct: number | null;
  writing_high_pct: number | null;
  maths_high_pct: number | null;
  gps_high_pct: number | null;

  // Progress Scores
  reading_progress: number | null;
  writing_progress: number | null;
  maths_progress: number | null;

  // Average Scores
  reading_avg_score: number | null;
  maths_avg_score: number | null;
  gps_avg_score: number | null;

  // School Context
  disadvantaged_pct: number | null;
  eal_pct: number | null;
  sen_support_pct: number | null;
  sen_ehcp_pct: number | null;
  stability_pct: number | null;

  // Pupil Absence from Tests
  reading_absence_pct: number | null;
  gps_absence_pct: number | null;
  maths_absence_pct: number | null;
  writing_absence_pct: number | null;
  science_absence_pct: number | null;

  // Gender Breakdown
  rwm_expected_boys_pct: number | null;
  rwm_expected_girls_pct: number | null;
  rwm_high_boys_pct: number | null;
  rwm_high_girls_pct: number | null;

  // Disadvantaged Performance
  rwm_expected_disadvantaged_pct: number | null;
  rwm_expected_non_disadvantaged_pct: number | null;
  disadvantaged_gap: number | null;

  // 3-Year Averages
  rwm_expected_3yr_pct: number | null;
  reading_avg_3yr: number | null;
  maths_avg_3yr: number | null;

  // KS4 / GCSE metrics
  attainment_8_score: number | null;
  progress_8_score: number | null;
  progress_8_lower_ci: number | null;
  progress_8_upper_ci: number | null;
  progress_8_english: number | null;
  progress_8_maths: number | null;
  progress_8_ebacc: number | null;
  progress_8_open: number | null;
  english_maths_strong_pass_pct: number | null;
  english_maths_standard_pass_pct: number | null;
  ebacc_entry_pct: number | null;
  ebacc_strong_pass_pct: number | null;
  ebacc_standard_pass_pct: number | null;
  ebacc_avg_score: number | null;
  gcse_grade_91_pct: number | null;
  prior_attainment_avg: number | null;
}

// ============================================================================
// API Response Types
// ============================================================================

export interface AbsenceData {
  overall_absence_rate: number | null;
  persistent_absence_rate: number | null;
}

export interface PaginationInfo {
  page: number;
  page_size: number;
  total: number;
  total_pages: number;
}

export interface ResultFilters {
  local_authorities: string[];
  school_types: string[];
  phases: string[];
  genders: string[];
  admissions_policies: string[];
}

export interface SchoolsResponse {
  schools: School[];
  page: number;
  page_size: number;
  total: number;
  total_pages: number;
  search_mode?: 'name' | 'location';
  result_filters?: ResultFilters;
  location_info?: {
    postcode: string;
    radius: number;
    coordinates: [number, number];
  };
}

export interface SchoolDetailsResponse {
  school_info: School;
  yearly_data: SchoolResult[];
  absence_data: AbsenceData | null;
  // Supplementary data (null until Kestra populates)
  ofsted: OfstedInspection | null;
  census: SchoolCensus | null;
  admissions: SchoolAdmissions | null;
  /** All available admissions years, oldest first. Drives the multi-year trend view. */
  admissions_history: SchoolAdmissions[];
  deprivation: SchoolDeprivation | null;
  finance: SchoolFinance | null;
}

export interface ComparisonData {
  school_info: School;
  yearly_data: SchoolResult[];
  // Supplementary blocks (additive; absent on an old backend)
  ofsted?: OfstedInspection | null;
  census?: SchoolCensus | null;
  admissions?: SchoolAdmissions | null;
  admissions_history?: SchoolAdmissions[];
  deprivation?: SchoolDeprivation | null;
}

export interface BenchmarkBlock {
  eal_pct: number | null;
  sen_support_pct: number | null;
  disadvantaged_pct: number | null;
  fsm_pct?: number | null;
  median_pupils: number | null;
  /** Primary only — weighted by cohort size. */
  disadvantaged_rwm_expected_pct?: number | null;
}

/** Computed from our dataset — NOT official DfE figures. UI copy must say
 * "state-school average (computed from our dataset)" (the `source` string). */
export interface Benchmarks {
  source: string;
  year: number;
  primary: BenchmarkBlock;
  secondary: BenchmarkBlock;
}

export interface NationalAverages {
  year: number;
  primary: Record<string, number>;
  secondary: Record<string, number>;
  by_year: Array<{
    year: number;
    primary: Record<string, number>;
    secondary: Record<string, number>;
  }>;
}

export interface ComparisonResponse {
  comparison: Record<string, ComparisonData>;
  national_averages?: NationalAverages;
  benchmarks?: Benchmarks;
}

export interface RankingItem {
  urn: number;
  school_name: string;
  local_authority: string;
  school_type?: string;
  value: number;
  rank?: number;
}

// Alias for backwards compatibility
export type RankingEntry = RankingItem;

export interface RankingsResponse {
  rankings: RankingItem[];
  metric: string;
  year?: number;
  local_authority?: string;
}

export interface Filters {
  local_authorities: string[];
  school_types: string[];
  years: number[];
  phases: string[];
  genders: string[];
  admissions_policies: string[];
}

export interface NationalAveragesYear {
  year: number;
  primary: Record<string, number>;
  secondary: Record<string, number>;
}

export interface NationalAverages extends NationalAveragesYear {
  /** Per-year averages for every year in the dataset, used for chart reference lines. */
  by_year: NationalAveragesYear[];
}

export interface LAaveragesResponse {
  year: number;
  secondary: {
    attainment_8_by_la: Record<string, number>;
  };
}

// Backend returns filters directly, not wrapped
export type FiltersResponse = Filters;

export interface MetricDefinition {
  key: string;
  label: string;
  description: string;
  category: 'expected' | 'higher' | 'progress' | 'average' | 'context' | 'absence' | 'gender' | 'disadvantaged' | '3yr';
  format: 'percentage' | 'score' | 'progress';
  hasNationalAverage?: boolean;
}

// Backend returns metrics as an array, not an object
export interface MetricsResponse {
  metrics: MetricDefinition[];
}

export interface DataInfoResponse {
  total_schools: number;
  years_available: number[];
  latest_year: number;
  total_records: number;
}

// ============================================================================
// API Request Parameter Types
// ============================================================================

export interface SchoolSearchParams {
  search?: string;
  local_authority?: string;
  school_type?: string;
  phase?: string;
  postcode?: string;
  radius?: number;
  page?: number;
  page_size?: number;
  gender?: string;
  admissions_policy?: string;
  has_sixth_form?: string;
}

export interface RankingsParams {
  metric: string;
  year?: number;
  local_authority?: string;
  limit?: number;
  phase?: string;
}

export interface ComparisonParams {
  urns: string | number[];
}

// ============================================================================
// UI State Types
// ============================================================================

export interface ComparisonState {
  selectedSchools: School[];
  selectedMetric: string;
}

export interface SearchState {
  mode: 'name' | 'location';
  query: string;
  filters: {
    local_authority: string;
    school_type: string;
  };
  postcode?: string;
  radius?: number;
  resultsView: 'list' | 'map';
}

export interface MapState {
  center: [number, number];
  zoom: number;
  bounds?: [[number, number], [number, number]];
}

// ============================================================================
// Chart Data Types
// ============================================================================

export interface ChartDataset {
  label: string;
  data: (number | null)[];
  borderColor: string;
  backgroundColor: string;
}

export interface ChartData {
  labels: (string | number)[];
  datasets: ChartDataset[];
}

// ============================================================================
// Error Types
// ============================================================================

export interface APIError {
  detail: string;
  status?: number;
}

// ============================================================================
// Utility Types
// ============================================================================

export type MetricKey = keyof Omit<SchoolResult, 'id' | 'school_id' | 'year'>;

export type SortDirection = 'asc' | 'desc';

export interface SortConfig {
  key: string;
  direction: SortDirection;
}
