package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"prsi/internal/api"
	"prsi/internal/llm"
	"strings"
)

func main() {
	hub := api.NewHub()

	// Static files
	http.Handle("/", http.FileServer(http.Dir("./web/static")))

	// WebSocket
	http.HandleFunc("/ws", hub.HandleWS)

	// Expose current script for a game room (used by the script viewer panel)
	http.HandleFunc("/api/script", hub.HandleGetScript)
	http.HandleFunc("/api/lobbies", hub.HandleListLobbies)

	// LLM rule-generation endpoint
	http.HandleFunc("/api/generate-rule", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}

		var req struct {
			CurrentScript string `json:"current_script"`
			RulePrompt    string `json:"rule_prompt"`
			WinnerName    string `json:"winner_name"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}
		if req.RulePrompt == "" {
			http.Error(w, "rule_prompt is required", http.StatusBadRequest)
			return
		}

		result, err := llm.GenerateRule(llm.GenerateRuleRequest{
			CurrentScript: req.CurrentScript,
			RulePrompt:    req.RulePrompt,
			WinnerName:    req.WinnerName,
		})
		if err != nil {
			log.Println("generate-rule error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(result)
	})

	addr := serverAddr()
	log.Printf("Server starting on %s", addr)
	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func serverAddr() string {
	port := strings.TrimSpace(os.Getenv("PORT"))
	if port == "" {
		port = strings.TrimSpace(os.Getenv("APP_PORT"))
	}
	if port == "" {
		port = "8080"
	}
	if strings.HasPrefix(port, ":") {
		return port
	}
	return ":" + port
}
