UPDATE model_catalog_providers
SET default_auth_type = 'APIKey',
    updated_at = now()
WHERE provider_key = 'keling'
   OR provider_code = 'keling';

UPDATE integration_platforms
SET auth_type = CASE
      WHEN COALESCE(NULLIF(trim(credentials->>'accessKey'), ''), NULLIF(trim(credentials->>'secretKey'), '')) IS NULL
        THEN 'APIKey'
      ELSE auth_type
    END,
    credentials = CASE
      WHEN credentials ? 'apiKey' THEN credentials
      ELSE credentials || '{"apiKey": ""}'::jsonb
    END,
    updated_at = now()
WHERE provider = 'keling'
  AND deleted_at IS NULL;

WITH keling_30_turbo AS (
  SELECT
    'keling:kling-3.0-turbo' AS canonical_model_key,
    'kling-3.0-turbo' AS provider_model_name,
    '可灵3.0 Turbo' AS display_name,
    '["video_generate","image_to_video"]'::jsonb AS model_type,
    '{
      "video_generate": {
        "aspect_ratio_allowed": ["16:9", "1:1", "9:16"],
        "output_resolutions": ["720p", "1080p"],
        "duration_range": [3, 15],
        "output_audio": true,
        "prompt_length_limit": {
          "max": 3072,
          "label": "可灵3.0 Turbo"
        }
      },
      "image_to_video": {
        "output_resolutions": ["720p", "1080p"],
        "duration_range": [3, 15],
        "input_first_frame": true,
        "input_last_frame": false,
        "input_first_last_frame": false,
        "aspect_ratio_allowed": [],
        "output_audio": true,
        "input_reference_generate_single": false,
        "input_reference_generate_multiple": false,
        "support_video_effect_template": false,
        "prompt_length_limit": {
          "max": 2500,
          "label": "可灵3.0 Turbo"
        }
      },
      "originalTypes": ["video_generate", "image_to_video"]
    }'::jsonb AS capabilities,
    COALESCE(
      (
        SELECT base_billing_config
        FROM base_model_catalog
        WHERE canonical_model_key = 'keling:kling-v3'
        LIMIT 1
      ),
      '{
        "video": {
          "basePrice": 100,
          "baseWeight": 1,
          "dynamicWeight": {
            "720p": 1,
            "1080p": 1.5,
            "audio-true": 2,
            "audio-false": 1
          }
        },
        "currency": "resource"
      }'::jsonb
    ) AS base_billing_config,
    COALESCE(
      (
        SELECT default_rate_limit_policy
        FROM base_model_catalog
        WHERE canonical_model_key = 'keling:kling-v3'
        LIMIT 1
      ),
      '{"platformLimits":{"max_concurrent_requests":5}}'::jsonb
    ) AS default_rate_limit_policy,
    '{
      "source": "server-main.integration-platform",
      "sourceProviderCode": "keling",
      "sourceProviderName": "可灵AI",
      "sourceSpecType": "keling",
      "originalTypes": ["video_generate", "image_to_video"],
      "alias": "可灵3.0 Turbo",
      "description": "可灵新任务 API 的 3.0 Turbo 文生视频与首帧图生视频模型",
      "iconPath": "https://static.51easyai.com/kling-color.webp",
      "billingType": "external-api",
      "billingMode": "",
      "referenceModel": "",
      "modelWeight": null,
      "selectable": true,
      "rawModel": {
        "name": "kling-3.0-turbo",
        "types": ["video_generate", "image_to_video"],
        "alias": "可灵3.0 Turbo",
        "icon_path": "https://static.51easyai.com/kling-color.webp"
      }
    }'::jsonb AS metadata
)
INSERT INTO base_model_catalog (
  provider_id,
  provider_key,
  canonical_model_key,
  provider_model_name,
  model_type,
  display_name,
  capabilities,
  base_billing_config,
  default_rate_limit_policy,
  metadata,
  catalog_type,
  default_snapshot,
  status
)
SELECT
  (
    SELECT id
    FROM model_catalog_providers
    WHERE provider_key = 'keling' OR provider_code = 'keling'
    LIMIT 1
  ),
  'keling',
  model.canonical_model_key,
  model.provider_model_name,
  model.model_type,
  model.display_name,
  model.capabilities,
  model.base_billing_config,
  model.default_rate_limit_policy,
  jsonb_set(model.metadata, '{rawModel,capabilities}', model.capabilities, true),
  'system',
  jsonb_build_object(
    'providerKey', 'keling',
    'canonicalModelKey', model.canonical_model_key,
    'providerModelName', model.provider_model_name,
    'modelType', model.model_type,
    'modelAlias', model.display_name,
    'displayName', model.display_name,
    'capabilities', model.capabilities,
    'baseBillingConfig', model.base_billing_config,
    'defaultRateLimitPolicy', model.default_rate_limit_policy,
    'metadata', jsonb_set(model.metadata, '{rawModel,capabilities}', model.capabilities, true),
    'status', 'active'
  ),
  'active'
FROM keling_30_turbo model
ON CONFLICT (canonical_model_key) DO UPDATE
SET provider_id = EXCLUDED.provider_id,
    provider_key = EXCLUDED.provider_key,
    provider_model_name = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.provider_model_name ELSE base_model_catalog.provider_model_name END,
    model_type = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.model_type ELSE base_model_catalog.model_type END,
    display_name = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.display_name ELSE base_model_catalog.display_name END,
    capabilities = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.capabilities ELSE base_model_catalog.capabilities END,
    base_billing_config = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.base_billing_config ELSE base_model_catalog.base_billing_config END,
    default_rate_limit_policy = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.default_rate_limit_policy ELSE base_model_catalog.default_rate_limit_policy END,
    metadata = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.metadata ELSE base_model_catalog.metadata END,
    catalog_type = CASE WHEN base_model_catalog.customized_at IS NULL THEN 'system' ELSE base_model_catalog.catalog_type END,
    default_snapshot = CASE WHEN base_model_catalog.customized_at IS NULL THEN EXCLUDED.default_snapshot ELSE base_model_catalog.default_snapshot END,
    status = CASE WHEN base_model_catalog.customized_at IS NULL THEN 'active' ELSE base_model_catalog.status END,
    updated_at = now();

INSERT INTO platform_models (
  platform_id,
  base_model_id,
  model_name,
  provider_model_name,
  model_alias,
  model_type,
  display_name,
  capabilities,
  pricing_mode,
  billing_config,
  retry_policy,
  rate_limit_policy,
  enabled
)
SELECT
  platform.id,
  base_model.id,
  base_model.provider_model_name,
  base_model.provider_model_name,
  base_model.display_name,
  base_model.model_type,
  base_model.display_name,
  base_model.capabilities,
  'inherit_discount',
  base_model.base_billing_config,
  '{"enabled":true,"maxAttempts":1}'::jsonb,
  base_model.default_rate_limit_policy,
  true
FROM integration_platforms platform
JOIN base_model_catalog base_model
  ON base_model.canonical_model_key = 'keling:kling-3.0-turbo'
WHERE platform.provider = 'keling'
  AND platform.deleted_at IS NULL
ON CONFLICT (platform_id, model_name) DO UPDATE
SET base_model_id = EXCLUDED.base_model_id,
    provider_model_name = EXCLUDED.provider_model_name,
    model_alias = EXCLUDED.model_alias,
    display_name = EXCLUDED.display_name,
    model_type = EXCLUDED.model_type,
    capabilities = EXCLUDED.capabilities,
    pricing_mode = EXCLUDED.pricing_mode,
    billing_config = EXCLUDED.billing_config,
    retry_policy = EXCLUDED.retry_policy,
    rate_limit_policy = EXCLUDED.rate_limit_policy,
    enabled = EXCLUDED.enabled,
    updated_at = now();
