// Package main generates the embedded AS info data for the asinfo package
package main

import (
	"encoding/csv"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

const asCsvURL = "https://github.com/ipverse/asn-info/raw/refs/heads/master/as.csv"

// ASInfo represents information about an Autonomous System
type ASInfo struct {
	ASN         int    `json:"asn"`
	Handle      string `json:"handle"`
	Description string `json:"description"`
}

func main() {
	// Configure logger to write to stderr
	log.SetOutput(os.Stderr)

	// Fetch the CSV data
	log.Println("Fetching AS CSV data...")
	resp, err := http.Get(asCsvURL)
	if err != nil {
		log.Fatalf("Failed to fetch CSV: %v", err)
	}
	defer func() {
		_ = resp.Body.Close()
	}()

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("Failed to fetch CSV: HTTP %d", resp.StatusCode)
	}

	// Parse CSV
	reader := csv.NewReader(resp.Body)

	// Read header
	header, err := reader.Read()
	if err != nil {
		log.Fatalf("Failed to read CSV header: %v", err)
	}

	if len(header) != 3 || header[0] != "asn" || header[1] != "handle" || header[2] != "description" {
		log.Fatalf("Unexpected CSV header: %v", header)
	}

	// Read all records
	var asInfos []ASInfo
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Printf("Error reading CSV record: %v", err)

			continue
		}

		const expectedFields = 3
		if len(record) != expectedFields {
			log.Printf("Skipping invalid record: %v", record)

			continue
		}

		asn, err := strconv.Atoi(record[0])
		if err != nil {
			log.Printf("Invalid ASN %q: %v", record[0], err)

			continue
		}

		asInfos = append(asInfos, ASInfo{
			ASN:         asn,
			Handle:      strings.TrimSpace(record[1]),
			Description: strings.TrimSpace(record[2]),
		})
	}

	log.Printf("Parsed %d AS records", len(asInfos))

	// Convert to JSON and output to stdout
	encoder := json.NewEncoder(os.Stdout)
	encoder.SetIndent("", "\t")
	if err := encoder.Encode(asInfos); err != nil {
		log.Fatalf("Failed to encode JSON: %v", err)
	}
}
