-- ailf.reports — one row per evaluation run
--
-- Clean passthrough view over the Airbyte-loaded raw table. The GROQ
-- projection in the Airbyte connector already flattens the nested Sanity
-- document, so this view mostly handles type casting and column ordering
-- to match the designed schema from bigquery.md.
--
-- Source: ailf_raw.reports (Airbyte stream: "reports")
-- Target: ailf.reports (this view)
--
-- Usage:
--   bq query --use_legacy_sql=false < views/reports.sql
--
-- @see docs/design-docs/report-store/bigquery.md

CREATE OR REPLACE VIEW `data-platform-302218.ailf.reports` AS
SELECT
  report_id,
  TIMESTAMP(completed_at)                         AS completed_at,
  CAST(duration_ms AS INT64)                      AS duration_ms,
  tag,
  title,
  mode,
  source_name,
  source_base_url,
  source_dataset,
  source_perspective,
  grader_model,
  trigger_type,
  trigger_caller_repo,
  git_repo,
  git_branch,
  git_sha,
  CAST(git_pr_number AS INT64)                    AS git_pr_number,
  ROUND(avg_score, 2)                             AS avg_score,
  ROUND(avg_doc_lift, 2)                          AS avg_doc_lift,
  ROUND(avg_actual_score, 2)                      AS avg_actual_score,
  ROUND(avg_retrieval_gap, 2)                     AS avg_retrieval_gap,
  ROUND(avg_infrastructure_efficiency, 4)         AS avg_infrastructure_efficiency,
  ROUND(total_cost, 4)                            AS total_cost,
  ROUND(grader_cost, 4)                           AS grader_cost,
  CAST(area_count AS INT64)                       AS area_count,
  CAST(model_count AS INT64)                      AS model_count,
  areas,
  models,
  promptfoo_url,
  promptfoo_urls,
  -- D0037 — run classification, ownership, executor, reproducibility.
  -- Nullable for historical rows predating the taxonomy.
  classification,
  owner_team,
  owner_individual,
  executor_type,
  executor_name,
  executor_surface,
  executor_github_actor,
  purpose,
  labels,
  lineage_rerun_of,
  lineage_compared_against,
  lineage_parent_job_id,
  tool_ailf_version,
  tool_node_version,
  host_platform,
  host_arch,
  host_ci,
  validity_status,
  validity_method,
  validity_ruleset_version,
  TIMESTAMP(validity_assessed_at)                 AS validity_assessed_at,
  validity_reasons,
  (validity_status IS NULL OR validity_status = 'ok') AND (classification IS NULL OR classification NOT IN ('test', 'experimental')) AS include_in_default_trends,
  TIMESTAMP(_createdAt)                           AS synced_at
FROM
  `data-platform-302218.ailf_raw.reports`;
