-- ailf.synthesis_parse_failure_rate_7d — per-card parse-failure rate over 7 days
--
-- Computes the Zod-schema parse-failure rate per Diagnosis card type over the
-- previous 7 days, sourced from the synthesis_per_card Airbyte stream. Any row
-- returned by this view represents a card type that breached the 2% threshold
-- defined in D6-18 and should trigger a manual investigation per the runbook.
--
-- Source: ailf_raw.synthesis_per_card (Airbyte stream: "synthesis_per_card")
-- Target: ailf.synthesis_parse_failure_rate_7d (this view)
--
-- Threshold: failure_rate > 0.02 (2%) over INTERVAL 7 DAY  [D6-18]
-- To change the threshold, edit the HAVING clause and WHERE clause below;
-- both are the single edit points per D6-18 (not lifted to config).
--
-- Usage:
--   bq query --use_legacy_sql=false < views/synthesis_parse_failure_rate_7d.sql
--
-- @see docs/runbooks/diagnosis-parse-failure-watch.md — operator runbook
-- @see packages/eval/config/airbyte/ai_literacy_framework.connector.yaml — synthesis_per_card stream

CREATE OR REPLACE VIEW `data-platform-302218.ailf.synthesis_parse_failure_rate_7d` AS
SELECT
  JSON_VALUE(card, '$.card_type')                                        AS card_type,
  COUNT(*)                                                               AS total_runs,
  COUNTIF(SAFE_CAST(JSON_VALUE(card, '$.parse_failed') AS BOOL))        AS parse_failures,
  ROUND(SAFE_DIVIDE(
    COUNTIF(SAFE_CAST(JSON_VALUE(card, '$.parse_failed') AS BOOL)),
    COUNT(*)
  ), 4)                                                                  AS failure_rate
FROM
  `data-platform-302218.ailf_raw.synthesis_per_card` AS r,
  UNNEST(JSON_QUERY_ARRAY(r.per_card)) AS card
WHERE
  r.completed_at IS NOT NULL
  AND TIMESTAMP(r.completed_at) >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
  AND JSON_VALUE(card, '$.card_type') IS NOT NULL
GROUP BY
  card_type
HAVING
  failure_rate > 0.02
ORDER BY
  failure_rate DESC
