package main

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

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)

	// 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)
	})

	log.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
