package handlers

import (
	"customServer/internal/protocol"
	"customServer/internal/state"
	"fmt"
	"net"
)

func HandleWhatsNewPussycatRequest(conn net.Conn, requestData []byte) ([]byte, int) {
	fmt.Println("[TCP] Handling WhatsNewPussycatRequest")

	mgr := state.GlobalManager
	if mgr.HasActiveGame() {
		activeGameID := mgr.GetActiveGameID()
		fmt.Printf("[TCP] StatusReport: Reporting Active Game %d\n", activeGameID)

		// StatusReport Message (Inner)
		innerReport := make([]byte, 0)

		// Field 1: GameId (int64)
		innerReport = append(innerReport, 0x08)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(activeGameID))...)

		// Field 2: Status (Enum) = 1 (IN_PROGRESS)
		innerReport = append(innerReport, 0x10)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(protocol.GameStatus_IN_PROGRESS))...)

		// Field 3: Data (Bytes) - Dynamic IronGameState
		dataBytes := state.GetMockIronGameStateBytes()
		innerReport = append(innerReport, 0x1a)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(len(dataBytes)))...)
		innerReport = append(innerReport, dataBytes...)

		// Field 4: TurnId (int32) = 4
		innerReport = append(innerReport, 0x20)
		innerReport = append(innerReport, protocol.EncodeVarint(4)...)

		// Field 5: NextPlayerIds (Repeated Int32)
		nextPlayers := []uint64{uint64(state.MockUserID)}
		npBytes := make([]byte, 0)
		for _, pid := range nextPlayers {
			npBytes = append(npBytes, protocol.EncodeVarint(pid)...)
		}
		innerReport = append(innerReport, 0x2a)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(len(npBytes)))...)
		innerReport = append(innerReport, npBytes...)

		// Field 6: Players (Repeated Player)
		mockPlayer := state.GetMockPlayerBytes()
		innerReport = append(innerReport, 0x32)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(len(mockPlayer)))...)
		innerReport = append(innerReport, mockPlayer...)

		// Field 14: Configuration (GameConfiguration)
		fallbackConfig := getFallbackConfigBytes()
		innerReport = append(innerReport, 0x72)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(len(fallbackConfig)))...)
		innerReport = append(innerReport, fallbackConfig...)

		// Field 16: ActivePlayer (Int32)
		innerReport = append(innerReport, 0x80, 0x01)
		innerReport = append(innerReport, protocol.EncodeVarint(uint64(state.MockUserID))...)

		// Wrap in GameStatusReportRequest (Field 1: repeated StatusReport)
		responsePayload := make([]byte, 0)
		responsePayload = append(responsePayload, 0x0a)
		responsePayload = append(responsePayload, protocol.EncodeVarint(uint64(len(innerReport)))...)
		responsePayload = append(responsePayload, innerReport...)

		return responsePayload, 512
	} else {
		fmt.Println("[TCP] StatusReport: Reporting Idle/Lobby State (Dynamic)")

		// Idle Status (Empty reports list)
		responsePayload := make([]byte, 0)
		return responsePayload, 512
	}
}
