package main

import (
	"database/sql"
	"fmt"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
	"go_rain_dtu/internal/dao"
	"go_rain_dtu/internal/handler"
	"go_rain_dtu/internal/tcp"
	"go_rain_dtu/pkg/logger"
)

const (
	username = "root"
	password = "root"
	host     = "localhost"
	port     = "3306"
	dbName   = "rain_db"
)

func main() {
	// 初始化日志
	if err := logger.InitLogger(); err != nil {
		fmt.Printf("初始化日志失败: %v\n", err)
		return
	}
	defer logger.CloseLogger()
	logger.StartLogRotation()

	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
		username, password, host, port, dbName)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		logger.Logger.Printf("连接数据库失败: %v", err)
		return
	}
	defer db.Close()

	// 初始化数据库表
	if err := initDB(db); err != nil {
		logger.Logger.Printf("初始化数据库表失败: %v", err)
		return
	}

	// 初始化各层
	sensorDAO := dao.NewSensorDAO(db)
	sensorHandler := handler.NewSensorHandler(sensorDAO)

	// 设置路由
	http.HandleFunc("/api/data", sensorHandler.GetAggregatedData)
	http.HandleFunc("/api/latest", sensorHandler.GetLatestData)
	http.HandleFunc("/api/status", sensorHandler.GetConnectionStatus)
	http.HandleFunc("/api/raw/latest", sensorHandler.GetLatestSensorRawData)
	http.HandleFunc("/api/trigger-query", sensorHandler.TriggerManualQuery)
	http.HandleFunc("/", sensorHandler.ServeStatic)

	// 启动TCP服务器
	go startTCPServer(sensorDAO)

	// 启动HTTP服务器
	logger.Logger.Println("HTTP服务器启动在 :10003")
	if err := http.ListenAndServe(":10003", nil); err != nil {
		logger.Logger.Printf("HTTP服务器启动失败: %v", err)
	}
}

func initDB(db *sql.DB) error {
	query := `
	CREATE TABLE IF NOT EXISTS sensor_data (
		id BIGINT PRIMARY KEY AUTO_INCREMENT,
		timestamp DATETIME NOT NULL,
		wind_speed INT,
		wind_force INT,
		wind_direction_8 INT,
		wind_direction_360 INT,
		humidity INT,
		temperature INT,
		atm_pressure INT,
		solar_radiation INT,
		rainfall INT,
		INDEX idx_timestamp (timestamp)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
	`

	_, err := db.Exec(query)
	return err
}

func startTCPServer(dao *dao.SensorDAO) {
	if err := tcp.StartTCPServer(dao); err != nil {
		logger.Logger.Printf("TCP服务器启动失败: %v", err)
	}
}
