package main

import (
	"git.yeij.top/AskaEth/Cyrene/pkg/logger"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"git.yeij.top/AskaEth/Cyrene/voice-service/internal/config"
	"git.yeij.top/AskaEth/Cyrene/voice-service/internal/handler"
	"git.yeij.top/AskaEth/Cyrene/voice-service/internal/service"
)

func main() {
	logger.SetDefault(logger.New("voice-service"))
	logger.Println("Voice-Service (STT + TTS) 启动中...")

	// 加载配置
	cfg := config.Load()

	logger.Printf("配置: 端口=%s, DashScope=%v, WhisperBinary=%s, WhisperModel=%s, Language=%s",
		cfg.Port, cfg.DashScopeAPIKey != "", cfg.WhisperBinary, cfg.WhisperModel, cfg.WhisperLanguage)

	// 初始化 STT 服务 (DashScope 优先, Whisper 回退)
	sttSvc := service.NewSTTService(cfg)

	if sttSvc.IsAvailable() {
		dashAvailable := cfg.DashScopeAPIKey != ""
		if dashAvailable {
			logger.Printf("STT: DashScope 实时=%s, 离线=%s + Whisper (回退)", cfg.DashScopeSTTRealtime, cfg.DashScopeModel)
		} else {
			logger.Println("STT: Whisper 本地引擎")
		}
	} else {
		logger.Printf("STT 引擎不可用。请配置 DASHSCOPE_API_KEY 或安装 Whisper")
		logger.Printf("  Whisper 安装: bash scripts/setup-whisper.sh")
	}

	// 初始化 TTS 服务
	ttsSvc := service.NewTTSService()

	if !ttsSvc.IsAvailable() {
		logger.Println("TTS 引擎不可用 (请安装: pip install edge-tts)")
	} else {
		ttsStatus := ttsSvc.GetEngineStatus()
		logger.Printf("TTS 引擎已就绪 (引擎: %s)", ttsStatus["engine"])
	}

	// 初始化 HTTP 处理器
	sttHandler := handler.NewSTTHandler(sttSvc, cfg)
	sttHandler.SetTTSService(ttsSvc)
	ttsHandler := handler.NewTTSHandler(ttsSvc)
	streamingHandler := handler.NewStreamingSTTHandler(sttSvc)

	// 注册路由
	mux := http.NewServeMux()
	sttHandler.RegisterRoutes(mux)
	ttsHandler.RegisterRoutes(mux)
	streamingHandler.RegisterStreamingRoutes(mux)

	// 启动 HTTP 服务
	srv := &http.Server{
		Addr:    ":" + cfg.Port,
		Handler: mux,
	}

	go func() {
		logger.Printf("Voice-Service 已启动在端口 %s", cfg.Port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Fatalf("服务启动失败: %v", err)
		}
	}()

	// 优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	logger.Println("正在关闭 Voice-Service...")
	srv.Close()
	logger.Println("Voice-Service 已关闭")
}
