CREATE TABLE IF NOT EXISTS model_runtime_policy_sets (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  policy_key text NOT NULL UNIQUE,
  name text NOT NULL,
  description text,
  rate_limit_policy jsonb NOT NULL DEFAULT '{}'::jsonb,
  retry_policy jsonb NOT NULL DEFAULT '{}'::jsonb,
  auto_disable_policy jsonb NOT NULL DEFAULT '{}'::jsonb,
  degrade_policy jsonb NOT NULL DEFAULT '{}'::jsonb,
  metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
  status text NOT NULL DEFAULT 'active',
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO model_runtime_policy_sets (
  policy_key, name, description, rate_limit_policy, retry_policy, auto_disable_policy, degrade_policy, metadata, status
)
VALUES (
  'default-runtime-v1',
  '默认运行策略',
  '默认 TPM/RPM/并发均不限制，仅保留失败重试、自动禁用和优先级降级策略。',
  '{"rules":[]}'::jsonb,
  '{"enabled":true,"maxAttempts":2,"allowKeywords":["rate_limit","timeout","server_error","network","429","5xx"],"denyKeywords":["invalid_api_key","insufficient_quota","billing_not_active","permission_denied"]}'::jsonb,
  '{"enabled":false,"threshold":3,"windowSeconds":300,"keywords":["invalid_api_key","account_deactivated","permission_denied","billing_not_active"]}'::jsonb,
  '{"enabled":true,"cooldownSeconds":300,"keywords":["rate_limit","quota","timeout","temporarily_unavailable","overloaded"]}'::jsonb,
  '{"seed":"0012_runtime_policy_sets"}'::jsonb,
  'active'
)
ON CONFLICT (policy_key) DO NOTHING;

ALTER TABLE IF EXISTS base_model_catalog
  ADD COLUMN IF NOT EXISTS runtime_policy_set_id uuid REFERENCES model_runtime_policy_sets(id) ON DELETE SET NULL,
  ADD COLUMN IF NOT EXISTS runtime_policy_override jsonb NOT NULL DEFAULT '{}'::jsonb;

ALTER TABLE IF EXISTS platform_models
  ADD COLUMN IF NOT EXISTS runtime_policy_set_id uuid REFERENCES model_runtime_policy_sets(id) ON DELETE SET NULL,
  ADD COLUMN IF NOT EXISTS runtime_policy_override jsonb NOT NULL DEFAULT '{}'::jsonb;

CREATE INDEX IF NOT EXISTS idx_base_model_catalog_runtime_policy
  ON base_model_catalog(runtime_policy_set_id);

CREATE INDEX IF NOT EXISTS idx_platform_models_runtime_policy
  ON platform_models(runtime_policy_set_id);

UPDATE base_model_catalog
SET runtime_policy_set_id = (
  SELECT id FROM model_runtime_policy_sets WHERE policy_key = 'default-runtime-v1' LIMIT 1
)
WHERE runtime_policy_set_id IS NULL
  AND EXISTS (SELECT 1 FROM model_runtime_policy_sets WHERE policy_key = 'default-runtime-v1');
