package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

func main() {
	key, site, integration := os.Getenv("READABLE_INGESTION_KEY"), os.Getenv("READABLE_SITE_ID"), os.Getenv("READABLE_INTEGRATION_ID")
	if key == "" || site == "" || integration == "" { panic("set Readable environment variables") }
	now := time.Now().UTC().Format(time.RFC3339Nano)
	run := fmt.Sprintf("%d", time.Now().UTC().UnixNano())
	batch := "batch:example-" + run
	payload := map[string]any{
		"schema": "readable.external-agentic.traffic", "version": 1, "site_id": site,
		"batch_id": batch, "created_at": now,
		"source": map[string]any{"type": "application_event", "provider": "generic",
			"integration_id": integration, "collector": "go-example", "collector_version": "1.0.0"},
		"event_count": 1, "events": []any{map[string]any{
			"event_id": "evt:example-" + run, "occurred_at": now,
			"request": map[string]any{"request_id": "request:example-" + run, "method": "GET", "scheme": "https",
				"hostname": "www.example.com", "path": "/products/example", "user_agent": "ChatGPT-User/1.0",
				"referrer_url": "https://chatgpt.com/"},
			"response": map[string]any{"status": 200, "content_type": "text/html", "duration_ms": 84, "bytes_sent": 18422},
			"extensions": map[string]any{},
		}},
	}
	body, _ := json.Marshal(payload)
	req, _ := http.NewRequest(http.MethodPost, "https://www.tryreadable.ai/api/external-agentic/traffic/batches", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+key); req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Idempotency-Key", batch); req.Header.Set("X-Readable-Ingestion-Version", "1")
	client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
	response, err := client.Do(req); if err != nil { panic(err) }; defer response.Body.Close()
	if response.StatusCode != http.StatusOK { panic(fmt.Sprintf("ingestion failed: %d", response.StatusCode)) }
	var receipt struct { Success, Accepted bool; SiteID string `json:"site_id"`; BatchID string `json:"batch_id"`; EventCount int `json:"event_count"`; Inserted int `json:"inserted"`; Deduplicated int `json:"deduplicated"`; Rejected int `json:"rejected"` }
	if err := json.NewDecoder(response.Body).Decode(&receipt); err != nil { panic(err) }
	if !receipt.Success || !receipt.Accepted || receipt.SiteID != site || receipt.BatchID != batch || receipt.EventCount != 1 || receipt.EventCount != receipt.Inserted+receipt.Deduplicated+receipt.Rejected { panic("invalid acknowledgement; retain the batch for retry") }
	fmt.Printf("%+v\n", receipt)
}
