-- 修复 llm_usage 表兼容性：旧库有 iPet 遗留的 kind/entry 列 (NOT NULL)，新库没有
-- kind/entry 保留为兼容字段，新代码写入默认值 ("llm_call" / null)
-- 1) 添加列（如果不存在）
ALTER TABLE llm_usage ADD COLUMN IF NOT EXISTS kind TEXT;
ALTER TABLE llm_usage ADD COLUMN IF NOT EXISTS entry JSONB;
-- 2) 只在列存在且 NOT NULL 时解除约束
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.columns
               WHERE table_name = 'llm_usage' AND column_name = 'kind' AND is_nullable = 'NO') THEN
        ALTER TABLE llm_usage ALTER COLUMN kind DROP NOT NULL;
    END IF;
    IF EXISTS (SELECT 1 FROM information_schema.columns
               WHERE table_name = 'llm_usage' AND column_name = 'entry' AND is_nullable = 'NO') THEN
        ALTER TABLE llm_usage ALTER COLUMN entry DROP NOT NULL;
    END IF;
END;
$$;
