-- Create autonomous scaling configuration table
-- This table stores the current state of autonomous capital-based scaling

CREATE TABLE IF NOT EXISTS autonomous_scaling_config (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    config_id UUID NOT NULL UNIQUE,
    enabled BOOLEAN DEFAULT TRUE,
    current_tier INTEGER NOT NULL,
    current_capital DECIMAL(20, 2) NOT NULL,
    current_symbols INTEGER NOT NULL,
    last_rebalance TIMESTAMPTZ NOT NULL,
    performance_30d JSONB NOT NULL,  -- PerformanceMetrics
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Create scaling tier history table for audit trail
CREATE TABLE IF NOT EXISTS scaling_tier_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_id UUID NOT NULL UNIQUE,
    from_tier INTEGER,  -- NULL for initial tier
    to_tier INTEGER NOT NULL,
    capital DECIMAL(20, 2) NOT NULL,
    reason TEXT NOT NULL,
    timestamp TIMESTAMPTZ DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX idx_autonomous_scaling_config_updated_at ON autonomous_scaling_config(updated_at DESC);
CREATE INDEX idx_scaling_tier_history_timestamp ON scaling_tier_history(timestamp DESC);
CREATE INDEX idx_scaling_tier_history_to_tier ON scaling_tier_history(to_tier);

-- Comments
COMMENT ON TABLE autonomous_scaling_config IS 'Autonomous capital-based scaling configuration and state';
COMMENT ON TABLE scaling_tier_history IS 'Audit trail of tier changes with reasons';
COMMENT ON COLUMN autonomous_scaling_config.current_tier IS 'Current capital tier (1-6)';
COMMENT ON COLUMN autonomous_scaling_config.performance_30d IS 'Rolling 30-day performance metrics (JSON)';
COMMENT ON COLUMN scaling_tier_history.reason IS 'Reason for tier change (performance, capital, manual)';
