package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

type HAR struct {
	Log struct {
		Entries []struct {
			WebSocketMessages []struct {
				Type string `json:"type"`
				Data string `json:"data"`
			} `json:"_webSocketMessages"`
		} `json:"entries"`
	} `json:"log"`
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: extract-queries <har-file>")
		os.Exit(1)
	}

	data, err := os.ReadFile(os.Args[1])
	if err != nil {
		fmt.Printf("Failed to read file: %v\n", err)
		os.Exit(1)
	}

	var har HAR
	if err := json.Unmarshal(data, &har); err != nil {
		fmt.Printf("Failed to parse HAR: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("=== WebSocket Messages ===\n")

	for _, entry := range har.Log.Entries {
		for i, msg := range entry.WebSocketMessages {
			if msg.Type == "send" {
				var payload map[string]interface{}
				if err := json.Unmarshal([]byte(msg.Data), &payload); err != nil {
					continue
				}

				msgType, _ := payload["type"].(string)
				fmt.Printf("[%d] Type: %s\n", i, msgType)

				if msgType == "subscribe" {
					if p, ok := payload["payload"].(map[string]interface{}); ok {
						if opName, ok := p["operationName"].(string); ok {
							fmt.Printf("    Operation: %s\n", opName)
						}
						if query, ok := p["query"].(string); ok {
							// Pretty print the query
							query = strings.ReplaceAll(query, "\\n", "\n")
							if len(query) > 500 {
								fmt.Printf("    Query:\n%s\n    [...truncated...]\n\n", query[:500])
							} else {
								fmt.Printf("    Query:\n%s\n\n", query)
							}
						}
					}
				} else {
					fmt.Println()
				}
			}
		}
	}
}

