-- === 05_fleet_metrics_tables.sql — Tables fleet_detections et ml_performance_metrics ===
--
-- fleet_detections     : résultats du détecteur de flottes §5.2 (JA4×ASN bipartite graph)
-- ml_performance_metrics : métriques de performance du pipeline ML par cycle
--
-- Appliquer avec :
--   clickhouse-client --multiquery < 05_fleet_metrics_tables.sql

-- --- fleet_detections ---
CREATE TABLE IF NOT EXISTS ja4_processing.fleet_detections
(
    detected_at     DateTime,
    community_id    UInt32,
    ja4_set         Array(String),
    asn_set         Array(String),
    fleet_score     Float32,
    n_ips           UInt32,
    ip_sample       Array(String),   -- échantillon des 20 premières IPs
    model_name      LowCardinality(String) DEFAULT ''
)
ENGINE = MergeTree
PARTITION BY toDate(detected_at)
ORDER BY (detected_at, community_id)
TTL detected_at + INTERVAL 7 DAY
SETTINGS ttl_only_drop_parts = 1;

-- --- ml_performance_metrics ---
CREATE TABLE IF NOT EXISTS ja4_processing.ml_performance_metrics
(
    cycle_at         DateTime,
    model_name       LowCardinality(String),
    total_sessions   UInt64,
    correlated_rate  Float32,
    anomaly_rate     Float32,
    critical_count   UInt32,
    high_count       UInt32,
    medium_count     UInt32,
    low_count        UInt32,
    known_bot_count  UInt32,
    anubis_deny_count UInt32,
    legit_browser_count UInt32,
    drift_rate       Float32,
    drift_alert      UInt8,
    cycle_latency_ms UInt32,
    features_valid   UInt16,
    features_total   UInt16,
    baseline_size    UInt32,
    threshold        Float32,
    meta_learner_active UInt8 DEFAULT 0
)
ENGINE = MergeTree
PARTITION BY toDate(cycle_at)
ORDER BY (cycle_at, model_name)
TTL cycle_at + INTERVAL 90 DAY
SETTINGS ttl_only_drop_parts = 1;
