CREATE TABLE route_decision_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    request_id TEXT NOT NULL,
    logical_group_id TEXT NOT NULL,
    public_model TEXT NOT NULL,
    user_key TEXT NOT NULL DEFAULT '',
    conversation_key TEXT NOT NULL DEFAULT '',
    sticky_key TEXT NOT NULL DEFAULT '',
    sticky_key_type TEXT NOT NULL DEFAULT '',
    sticky_hit INTEGER NOT NULL DEFAULT 0,
    selected_route_id TEXT NOT NULL,
    selected_shadow_group_id TEXT NOT NULL,
    fallback_used INTEGER NOT NULL DEFAULT 0,
    error_class TEXT NOT NULL DEFAULT '',
    upstream_status INTEGER NOT NULL DEFAULT 0,
    latency_ms INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_route_decision_logs_request_id ON route_decision_logs(request_id);
CREATE INDEX idx_route_decision_logs_group_model ON route_decision_logs(logical_group_id, public_model, id DESC);
CREATE INDEX idx_route_decision_logs_selected_route ON route_decision_logs(selected_route_id, id DESC);

CREATE TABLE route_failover_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    request_id TEXT NOT NULL,
    logical_group_id TEXT NOT NULL,
    public_model TEXT NOT NULL,
    from_route_id TEXT NOT NULL,
    to_route_id TEXT NOT NULL,
    reason TEXT NOT NULL,
    failure_count INTEGER NOT NULL DEFAULT 0,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_route_failover_events_request_id ON route_failover_events(request_id);
CREATE INDEX idx_route_failover_events_group_model ON route_failover_events(logical_group_id, public_model, id DESC);

CREATE TABLE route_sticky_audit (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    sticky_key TEXT NOT NULL,
    sticky_key_type TEXT NOT NULL,
    logical_group_id TEXT NOT NULL,
    public_model TEXT NOT NULL,
    route_id TEXT NOT NULL,
    action TEXT NOT NULL,
    expires_at TEXT NOT NULL DEFAULT '',
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_route_sticky_audit_sticky_key ON route_sticky_audit(sticky_key, id DESC);
CREATE INDEX idx_route_sticky_audit_group_model ON route_sticky_audit(logical_group_id, public_model, id DESC);
