-- session_capability_growth: vista que mide el ciclo "crear+usar" por sesion.
-- Una funcion se considera "creada en sesion X" si el primer code_writes
-- registrado para ese function_id (a nivel global) ocurrio dentro de la sesion X.
-- Una funcion "usada en sesion X" = >=1 fila en calls con misma sesion y ts >= created_at.
--
-- Lectura: created_this_session = COUNT(*) WHERE session_id = ?
--          used = COUNT(*) WHERE session_id = ? AND calls_in_session > 0
--          orphan = COUNT(*) WHERE session_id = ? AND calls_in_session = 0
--
-- Issue 0086. Aditivo. No reescribe schema previo.

CREATE VIEW IF NOT EXISTS session_capability_growth AS
WITH first_write AS (
    SELECT
        cw.function_id,
        cw.session_id,
        cw.ts AS created_at
    FROM code_writes cw
    WHERE cw.function_id != ''
      AND cw.ts = (
          SELECT MIN(ts) FROM code_writes
          WHERE function_id = cw.function_id
      )
)
SELECT
    fw.session_id,
    fw.function_id,
    fw.created_at,
    (SELECT MIN(c.ts) FROM calls c
        WHERE c.function_id = fw.function_id
          AND c.session_id = fw.session_id
          AND c.ts >= fw.created_at)        AS first_call_at,
    (SELECT COUNT(*) FROM calls c
        WHERE c.function_id = fw.function_id
          AND c.session_id = fw.session_id
          AND c.ts >= fw.created_at)        AS calls_in_session
FROM first_write fw;
