/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.config
 * @ClassName: PostgreSQLVectorInitializer
 * @Description: PostgreSQL向量扩展初始化器，确保pgvector扩展已安装
 * @Author: 张志锋
 * @Date: 2025-10-31
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.Statement;

/**
 * PostgreSQL向量扩展初始化器
 */
@Component
@ConditionalOnProperty(name = "vectorize.enabled", havingValue = "true", matchIfMissing = true)
public class PostgreSQLVectorInitializer {

    private static final Logger logger = LoggerFactory.getLogger(PostgreSQLVectorInitializer.class);

    @Value("${spring.datasource.url:jdbc:postgresql://127.0.0.1:5432/gdyd_zhpb_zgf}")
    private String pgsqlUrl;

    @Value("${spring.datasource.username:postgres}")
    private String pgsqlUsername;

    @Value("${spring.datasource.password:123456}")
    private String pgsqlPassword;

    @PostConstruct
    public void init() {
        try {
            // 连接到目标数据库并创建扩展
            try (Connection conn = java.sql.DriverManager.getConnection(pgsqlUrl, pgsqlUsername, pgsqlPassword)) {
                try (Statement stmt = conn.createStatement()) {
                    // 创建pgvector扩展
                    stmt.execute("CREATE EXTENSION IF NOT EXISTS vector");
                    logger.info("PostgreSQL pgvector扩展初始化成功");
                }
            }
        } catch (Exception e) {
            logger.warn("PostgreSQL pgvector扩展初始化失败，可能未安装pgvector扩展: {}", e.getMessage());
            logger.warn("请手动在PostgreSQL中执行: CREATE EXTENSION IF NOT EXISTS vector;");
            logger.warn("如果pgvector未安装，请参考: https://github.com/pgvector/pgvector");
        }
    }
}

