-- Normalized stat_series observations parsed from DOM.RF XLSX files.
-- Source: domrf_xlsx_files (BYTEA archive) → parsed via 36_parse_xlsx_stats.py.
-- Long-form panel: (territory × indicator × month) → numeric value.

-- sheet_code alone isn't unique — '01_01_01' appears in both
-- stockvariablesexsales (МКД 214-ФЗ без эскроу) and stockvariableskrt (МКД КРТ).
-- Composite PK on (file_name, sheet_code) keeps them separate.
CREATE TABLE IF NOT EXISTS domrf_stat_series_indicators (
    file_name        TEXT NOT NULL,               -- source xlsx
    sheet_code       TEXT NOT NULL,               -- '01_01_01' .. '01_04_NN'
    indicator_name   TEXT NOT NULL,               -- human label from row 2
    section_title    TEXT,                        -- top-of-file context
    n_periods        INT,                         -- # of monthly columns
    n_territories    INT,
    PRIMARY KEY (file_name, sheet_code)
);

CREATE TABLE IF NOT EXISTS domrf_stat_series_observations (
    snapshot_date    DATE NOT NULL,
    file_name        TEXT NOT NULL,
    sheet_code       TEXT NOT NULL,
    territory        TEXT NOT NULL,                -- 'Российская Федерация' | ФО | регион
    obs_date         DATE NOT NULL,                -- first day of month
    value            NUMERIC,
    PRIMARY KEY (snapshot_date, file_name, sheet_code, territory, obs_date)
);
CREATE INDEX IF NOT EXISTS idx_stat_obs_sheet     ON domrf_stat_series_observations (file_name, sheet_code);
CREATE INDEX IF NOT EXISTS idx_stat_obs_territory ON domrf_stat_series_observations (territory, obs_date);
CREATE INDEX IF NOT EXISTS idx_stat_obs_date      ON domrf_stat_series_observations (obs_date);
