package handlers

import (
	"net/http"
	"runtime"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"sproutclaw-web/internal/config"
	"sproutclaw-web/internal/services"
)

var terminalUpgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

// RegisterTerminal registers web terminal routes.
func RegisterTerminal(r *gin.RouterGroup, cfg *config.Config) {
	r.GET("/terminal", handleTerminalInfo(cfg))
	r.GET("/terminal/ws", handleTerminalWS(cfg))
}

func handleTerminalInfo(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"repoRoot": cfg.RepoRoot,
			"platform": runtime.GOOS,
		})
	}
}

func handleTerminalWS(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		conn, err := terminalUpgrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			return
		}
		defer conn.Close()

		if err := services.ServeWebTerminal(conn, cfg.RepoRoot); err != nil {
			_ = conn.WriteJSON(gin.H{"type": "error", "error": err.Error()})
		}
	}
}
