-- ============================================================================
-- SCRIPT DE DÉPLOIEMENT DES VUES DE DÉTECTION (CLICKHOUSE) - MABASE_PROD
-- ============================================================================

DROP TABLE IF EXISTS mabase_prod.ml_detected_anomalies;
DROP VIEW IF EXISTS mabase_prod.view_ai_features_1h;
DROP VIEW IF EXISTS mabase_prod.view_host_ip_ja4_rotation;
DROP VIEW IF EXISTS mabase_prod.view_host_ja4_anomalies;
DROP VIEW IF EXISTS mabase_prod.view_form_bruteforce_detected;
DROP VIEW IF EXISTS mabase_prod.view_alpn_mismatch_detected;
DROP VIEW IF EXISTS mabase_prod.view_tcp_spoofing_detected;
DROP VIEW IF EXISTS mabase_prod.mv_agg_host_ip_ja4_1h;
DROP TABLE IF EXISTS mabase_prod.agg_host_ip_ja4_1h;
DROP VIEW IF EXISTS mabase_prod.mv_agg_header_fingerprint_1h;
DROP TABLE IF EXISTS mabase_prod.agg_header_fingerprint_1h;

-- ----------------------------------------------------------------------------
-- 1. TABLES D'AGRÉGATION ET VUES MATÉRIALISÉES
-- ----------------------------------------------------------------------------

CREATE TABLE mabase_prod.agg_host_ip_ja4_1h (
    window_start DateTime,
    src_ip String,
    ja4 String,
    host String,
    first_seen SimpleAggregateFunction(min, DateTime),
    last_seen SimpleAggregateFunction(max, DateTime),
    hits SimpleAggregateFunction(sum, UInt64),
    count_post SimpleAggregateFunction(sum, UInt64),
    uniq_paths AggregateFunction(uniq, String),
    uniq_query_params AggregateFunction(uniq, String),
    src_country_code SimpleAggregateFunction(any, String),
    tcp_fingerprint SimpleAggregateFunction(any, String),
    tcp_jitter_variance AggregateFunction(varPop, Float64),
    tcp_window_size SimpleAggregateFunction(any, UInt32),
    tcp_window_scale SimpleAggregateFunction(any, UInt32),
    tcp_mss SimpleAggregateFunction(any, UInt32),
    tcp_ttl SimpleAggregateFunction(any, UInt32),
    http_version SimpleAggregateFunction(any, String),
    tls_alpn SimpleAggregateFunction(any, String),
    tls_sni SimpleAggregateFunction(any, String),
    first_ua SimpleAggregateFunction(any, String),
    correlated SimpleAggregateFunction(max, UInt8),
    unique_src_ports AggregateFunction(uniq, UInt16),
    max_keepalives SimpleAggregateFunction(max, UInt32),
    orphan_count SimpleAggregateFunction(sum, UInt64)
) ENGINE = AggregatingMergeTree()
ORDER BY (window_start, src_ip, ja4, host)
TTL window_start + INTERVAL 7 DAY;

CREATE MATERIALIZED VIEW mabase_prod.mv_agg_host_ip_ja4_1h TO mabase_prod.agg_host_ip_ja4_1h AS
SELECT
    toStartOfHour(src.time) AS window_start,
    src.src_ip, src.ja4, src.host,
    min(src.time) AS first_seen, max(src.time) AS last_seen,
    count() AS hits,
    sum(IF(src.method = 'POST', 1, 0)) AS count_post,
    uniqState(src.path) AS uniq_paths,
    uniqState(src.query) AS uniq_query_params,
    any(src.src_country_code) AS src_country_code,
    any(toString(cityHash64(concat(toString(src.tcp_meta_window_size), toString(src.tcp_meta_mss), toString(src.tcp_meta_window_scale), src.tcp_meta_options)))) AS tcp_fingerprint,
    varPopState(toFloat64(src.syn_to_clienthello_ms)) AS tcp_jitter_variance,
    any(src.tcp_meta_window_size) AS tcp_window_size,
    any(src.tcp_meta_window_scale) AS tcp_window_scale,
    any(src.tcp_meta_mss) AS tcp_mss,
    any(src.ip_meta_ttl) AS tcp_ttl,
    any(src.http_version) AS http_version,
    any(src.tls_alpn) AS tls_alpn,
    any(src.tls_sni) AS tls_sni,
    any(src.header_user_agent) AS first_ua,
    max(toUInt8(src.correlated)) AS correlated,
    uniqState(toUInt16(src.src_port)) AS unique_src_ports,
    max(toUInt32(src.keepalives)) AS max_keepalives,
    sum(IF(src.orphan_side = 'A' OR toUInt8(src.correlated) = 0, 1, 0)) AS orphan_count
FROM mabase_prod.http_logs AS src
GROUP BY window_start, src.src_ip, src.ja4, src.host;

CREATE TABLE mabase_prod.agg_header_fingerprint_1h (
    window_start DateTime,
    src_ip String,
    header_order_hash SimpleAggregateFunction(any, String),
    header_count SimpleAggregateFunction(max, UInt16),
    has_accept_language SimpleAggregateFunction(max, UInt8),
    has_cookie SimpleAggregateFunction(max, UInt8),
    has_referer SimpleAggregateFunction(max, UInt8), -- NOUVEAU (JA4H_a)
    modern_browser_score SimpleAggregateFunction(max, UInt8),
    sec_fetch_mode SimpleAggregateFunction(any, String),
    sec_fetch_dest SimpleAggregateFunction(any, String),
    count_site_none SimpleAggregateFunction(sum, UInt64)
) ENGINE = AggregatingMergeTree()
ORDER BY (window_start, src_ip)
TTL window_start + INTERVAL 7 DAY;

CREATE MATERIALIZED VIEW mabase_prod.mv_agg_header_fingerprint_1h TO mabase_prod.agg_header_fingerprint_1h AS
SELECT
    toStartOfHour(src.time) AS window_start,
    src.src_ip,
    any(toString(cityHash64(src.client_headers))) AS header_order_hash,
    max(toUInt16(length(src.client_headers) - length(replaceAll(src.client_headers, ',', '')) + 1)) AS header_count,
    max(toUInt8(if(position(src.client_headers, 'Accept-Language') > 0, 1, 0))) AS has_accept_language,
    max(toUInt8(if(position(src.client_headers, 'Cookie') > 0, 1, 0))) AS has_cookie,
    max(toUInt8(if(position(src.client_headers, 'Referer') > 0, 1, 0))) AS has_referer, -- NOUVEAU (JA4H_a)
    max(toUInt8(if(length(src.header_sec_ch_ua) > 0, 100, if(length(src.header_user_agent) > 0, 50, 0)))) AS modern_browser_score,
    any(src.header_sec_fetch_mode) AS sec_fetch_mode,
    any(src.header_sec_fetch_dest) AS sec_fetch_dest,
    sum(IF(src.header_sec_fetch_site = 'none', 1, 0)) AS count_site_none
FROM mabase_prod.http_logs AS src
GROUP BY window_start, src.src_ip;

-- ----------------------------------------------------------------------------
-- 2. TABLE DES ANOMALIES ÉLARGIE POUR GRAFANA
-- ----------------------------------------------------------------------------
CREATE TABLE mabase_prod.ml_detected_anomalies (
    detected_at DateTime,
    src_ip String,
    ja4 String,
    host String,
    anomaly_score Float32,
    
    -- Dimensions Applicatives et Comportementales
    hits UInt64,
    hit_velocity Float32,
    fuzzing_index Float32,
    post_ratio Float32,
    site_none_ratio Float32,
    
    -- Dimensions Réseau / TCP
    port_exhaustion_ratio Float32,
    max_keepalives UInt32,
    orphan_ratio Float32,
    tcp_jitter_variance Float32,
    tcp_shared_count UInt32,
    true_window_size UInt64,
    window_mss_ratio Float32,
    
    -- Dimensions TLS / Contextuelles
    alpn_http_mismatch UInt8,
    is_alpn_missing UInt8,
    sni_host_mismatch UInt8,
    
    -- Dimensions JA4H (Headers)
    header_count UInt16,
    has_accept_language UInt8,
    has_cookie UInt8,
    has_referer UInt8,
    modern_browser_score UInt8,
    is_headless UInt8,
    header_order_shared_count UInt32, -- NOUVEAU (JA4H_b)
    
    reason String
) ENGINE = MergeTree()
ORDER BY (detected_at, src_ip, ja4)
TTL detected_at + INTERVAL 30 DAY;

-- ----------------------------------------------------------------------------
-- 3. VUE DE FEATURE ENGINEERING POUR L'IA (SUR 24H)
-- ----------------------------------------------------------------------------
CREATE OR REPLACE VIEW mabase_prod.view_ai_features_1h AS
SELECT 
    a.src_ip, a.ja4, a.host, a.hits, a.uniq_paths, a.uniq_query_params, a.count_post,
    a.correlated AS correlated,

    (a.count_post / (a.hits + 1)) AS post_ratio,
    (a.uniq_query_params / (a.uniq_paths + 1)) AS fuzzing_index,
    (a.hits / (dateDiff('second', a.first_seen, a.last_seen) + 1)) AS hit_velocity,
    (a.unique_src_ports / (a.hits + 1)) AS port_exhaustion_ratio,
    (a.orphan_count / (a.hits + 1)) AS orphan_ratio,
    a.max_keepalives AS max_keepalives,

    COALESCE(a.tcp_jitter_variance, 0) AS tcp_jitter_variance,
    count() OVER (PARTITION BY a.tcp_fingerprint) AS tcp_shared_count,
    a.tcp_window_size * exp2(a.tcp_window_scale) AS true_window_size,
    IF(a.tcp_mss > 0, a.tcp_window_size / a.tcp_mss, 0) AS window_mss_ratio,

    IF(a.tls_alpn = 'h2' AND a.http_version!= '2', 1, 0) AS alpn_http_mismatch,
    IF(length(a.tls_alpn) = 0 OR a.tls_alpn = '00', 1, 0) AS is_alpn_missing,
    IF(length(a.tls_sni) > 0 AND a.tls_sni!= a.host, 1, 0) AS sni_host_mismatch,

    COALESCE(h.header_count, 0) AS header_count,
    COALESCE(h.has_accept_language, 0) AS has_accept_language,
    COALESCE(h.has_cookie, 0) AS has_cookie,
    COALESCE(h.has_referer, 0) AS has_referer,
    COALESCE(h.modern_browser_score, 0) AS modern_browser_score,
    IF(h.sec_fetch_mode = 'navigate' AND h.sec_fetch_dest!= 'document', 1, 0) AS is_fake_navigation,
    (h.count_site_none / (a.hits + 1)) AS site_none_ratio,
    
    -- JA4H_b : Regroupement par ordre de header pour détecter les botnets
    count() OVER (PARTITION BY h.header_order_hash) AS header_order_shared_count

FROM (
    SELECT
        window_start, src_ip, ja4, host,
        sum(hits) AS hits,
        uniqMerge(uniq_paths) AS uniq_paths,
        uniqMerge(uniq_query_params) AS uniq_query_params,
        sum(count_post) AS count_post,
        min(first_seen) AS first_seen,
        max(last_seen) AS last_seen,
        any(tcp_fingerprint) AS tcp_fingerprint,
        varPopMerge(tcp_jitter_variance) AS tcp_jitter_variance,
        any(tcp_window_size) AS tcp_window_size,
        any(tcp_window_scale) AS tcp_window_scale,
        any(tcp_mss) AS tcp_mss,
        any(http_version) AS http_version,
        any(tls_alpn) AS tls_alpn,
        any(tls_sni) AS tls_sni,
        max(correlated) AS correlated,
        uniqMerge(unique_src_ports) AS unique_src_ports,
        max(max_keepalives) AS max_keepalives,
        sum(orphan_count) AS orphan_count
    FROM mabase_prod.agg_host_ip_ja4_1h
    WHERE window_start >= toStartOfHour(now() - INTERVAL 24 HOUR)
    GROUP BY window_start, src_ip, ja4, host
) a
LEFT JOIN (
    SELECT
        window_start, src_ip,
        any(header_order_hash) AS header_order_hash,
        max(header_count) AS header_count,
        max(has_accept_language) AS has_accept_language,
        max(has_cookie) AS has_cookie,
        max(has_referer) AS has_referer,
        max(modern_browser_score) AS modern_browser_score,
        any(sec_fetch_mode) AS sec_fetch_mode,
        any(sec_fetch_dest) AS sec_fetch_dest,
        sum(count_site_none) AS count_site_none
    FROM mabase_prod.agg_header_fingerprint_1h
    WHERE window_start >= toStartOfHour(now() - INTERVAL 24 HOUR)
    GROUP BY window_start, src_ip
) h
ON a.src_ip = h.src_ip AND a.window_start = a.window_start;
