-- GPT Image 系列支持 OpenAI-compatible quality 参数；其他图像模型默认不声明，
-- runner 会在参数预处理时移除未支持模型上的 quality。

CREATE OR REPLACE FUNCTION pg_temp._tmp_enable_image_quality_control(capabilities jsonb)
RETURNS jsonb AS $$
DECLARE
  out jsonb := COALESCE(capabilities, '{}'::jsonb);
BEGIN
  IF out ? 'image_generate' THEN
    out := jsonb_set(out, '{image_generate,support_quality_control}', 'true'::jsonb, true);
  END IF;
  IF out ? 'image_edit' THEN
    out := jsonb_set(out, '{image_edit,support_quality_control}', 'true'::jsonb, true);
  END IF;
  RETURN out;
END;
$$ LANGUAGE plpgsql;

UPDATE base_model_catalog
SET capabilities = pg_temp._tmp_enable_image_quality_control(capabilities),
    default_snapshot = CASE
      WHEN COALESCE(default_snapshot, '{}'::jsonb) = '{}'::jsonb THEN default_snapshot
      WHEN jsonb_typeof(default_snapshot->'metadata'->'rawModel'->'capabilities') = 'object' THEN jsonb_set(
        jsonb_set(
          default_snapshot,
          '{capabilities}',
          pg_temp._tmp_enable_image_quality_control(COALESCE(default_snapshot->'capabilities', '{}'::jsonb)),
          true
        ),
        '{metadata,rawModel,capabilities}',
        pg_temp._tmp_enable_image_quality_control(COALESCE(default_snapshot->'metadata'->'rawModel'->'capabilities', '{}'::jsonb)),
        true
      )
      ELSE jsonb_set(
        default_snapshot,
        '{capabilities}',
        pg_temp._tmp_enable_image_quality_control(COALESCE(default_snapshot->'capabilities', '{}'::jsonb)),
        true
      )
    END,
    metadata = CASE
      WHEN jsonb_typeof(metadata->'rawModel'->'capabilities') = 'object' THEN jsonb_set(
        metadata,
        '{rawModel,capabilities}',
        pg_temp._tmp_enable_image_quality_control(COALESCE(metadata->'rawModel'->'capabilities', '{}'::jsonb)),
        true
      )
      ELSE metadata
    END,
    updated_at = now()
WHERE provider_model_name IN ('gpt-image-1', 'gpt-image-1.5', 'gpt-image-2')
  AND capabilities ?| ARRAY['image_generate', 'image_edit'];

UPDATE platform_models
SET capabilities = pg_temp._tmp_enable_image_quality_control(capabilities),
    updated_at = now()
WHERE COALESCE(NULLIF(provider_model_name, ''), model_name) IN ('gpt-image-1', 'gpt-image-1.5', 'gpt-image-2')
  AND capabilities ?| ARRAY['image_generate', 'image_edit'];

DROP FUNCTION pg_temp._tmp_enable_image_quality_control(jsonb);
