package com.lanyuanxiaoyao.bookstore;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.dialect.impl.MysqlDialect;
import com.lanyuanxiaoyao.service.template.helper.SnowflakeIdGenerator;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import lombok.extern.slf4j.Slf4j;

/**
 * 更新章节
 *
 * @author lanyuanxiaoyao
 * @version 20251031
 */
@Slf4j
public class UpdateIntoDatabase {
  public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
    var chapters = new ArrayList<Chapter>();
    Files.list(Path.of("out"))
        .sorted(Comparator.comparing(path -> FileUtil.lastModifiedTime(path.toFile())))
        .forEach(path -> {
          try {
            chapters.add(new Chapter(
                path.getFileName().toString(),
                Files.readString(path)
            ));
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        });
    Class.forName("com.mysql.cj.jdbc.Driver");
    try (
        var connection = DriverManager.getConnection(
            "jdbc:mysql://mysql.lanyuanxiaoyao.com:43780/bookstore?useUnicode=true&characterEncoding=utf8&useSSL=false",
            "bookstore",
            "EzSn+RZ*x2&fHFh9kC+H"
        )
        /*var ds = new SimpleDataSource(
            "jdbc:mysql://mysql.lanyuanxiaoyao.com:43780/bookstore?useUnicode=true&characterEncoding=utf8&useSSL=false",
            "bookstore",
            "EzSn+RZ*x2&fHFh9kC+H",
            "com.mysql.cj.jdbc.Driver"
        )*/
    ) {
      var dialect = new MysqlDialect();
      for (int index = 0; index < chapters.size(); index++) {
        var chapter = chapters.get(index);
        log.info("Chapter: {}", chapter.title());
        var now = LocalDateTime.now();
        var chapterId = SnowflakeIdGenerator.Snowflake.next();
        /*Db.use(ds, dialect).insert(
            Entity.create("bookstore_chapter")
                .set("id", chapterId)
                .set("created_time", now)
                .set("modified_time", now)
                .set("sequence", index)
                .set("book_id", 3608359126886400L)
        );*/
        try (var statement = connection.prepareStatement("insert into bookstore_chapter(id,created_time,modified_time,sequence,book_id) values(?,current_timestamp(),current_timestamp(),?,?)")) {
          statement.setLong(1, chapterId);
          statement.setDouble(2, index);
          statement.setLong(3, 3608359126886400L);
          statement.execute();
        }
        var lines = StrUtil.split(chapter.content, "\n")
            .stream()
            .map(StrUtil::trimToNull)
            .filter(ObjectUtil::isNotNull)
            .toList();
        // var entities = new ArrayList<Entity>();
        for (int lineIndex = 0; lineIndex < lines.size(); lineIndex++) {
          /*entities.add(
              Entity.create("bookstore_line")
                  .set("id", SnowflakeIdGenerator.Snowflake.next())
                  .set("created_time", now)
                  .set("modified_time", now)
                  .set("sequence", lineIndex)
                  .set("text", lines.get(lineIndex))
                  .set("chapter_id", chapterId)
          );*/
          try (var statement = connection.prepareStatement("insert into bookstore_line(id,created_time,modified_time,sequence,text,chapter_id) values(?,current_timestamp(),current_timestamp(),?,?,?)")) {
            statement.setLong(1, SnowflakeIdGenerator.Snowflake.next());
            statement.setDouble(2, lineIndex);
            statement.setString(3, lines.get(lineIndex));
            statement.setLong(4, chapterId);
            statement.execute();
          }
        }
        // Db.use(ds, dialect).insert(entities);
      }
    }

    /*var response = AIUtil.chat(
        new AIConfigBuilder(ModelName.OPENAI.getValue())
            .setApiUrl("http://127.0.0.1:30000")
            .setApiKey("*XMySqV%>hR&v>>g*NwCs3tpQ5FVMFEF2VHVTj<MYQd$&@$sY7CgqNyea4giJi4")
            .setModel("")
            .setTimout(1000 * 60 * 5)
            .build(),
        """
            —————
            上述是小说一个章节的内容，需要你为章节拟2句金庸武侠风格的七言绝句作为章节标题，标题在精确概括章节内容外也需要充满文学性、浪漫性，直接输出标题文字，除了标题外严禁输出任何无关的文字，禁止输出任何markdown格式
            """
    );
    log.info("response: {}", response);*/
  }

  public record Chapter(String title, String content) {
  }
}
