package main

import (
	"bytes"
	"fmt"
	"math/rand"
	"net"
	"os"
	"time"
)

func getRandomAddress() string {
	ip1 := rand.Intn(256)
	ip2 := rand.Intn(256)
	ip3 := rand.Intn(256)
	ip4 := rand.Intn(256)
	return fmt.Sprintf("%d.%d.%d.%d", ip1, ip2, ip3, ip4)
}

func offgas(r rune) {
	address := getRandomAddress()
	conn, err := net.Dial("udp", address+":7")
	if err != nil {
		fmt.Println("Error connecting to:", address, err)
	}
	defer conn.Close()

	// Set write timeout
	conn.SetWriteDeadline(time.Now().Add(3 * time.Second))

	// Send the character
	_, err = conn.Write([]byte(string(r)))
	if err != nil {
		fmt.Println("Error sending data to:", address, err)
		return
	}
}

func main() {
	// get poem.txt and index.html locations from args, if possible
	poemFile := "poem.txt"
	indexFile := "index.html"
	if len(os.Args) == 3 {
		poemFile = os.Args[1]
		indexFile = os.Args[2]
	}

	// get string from poem.txt
	str, err := os.ReadFile(poemFile)
	if err != nil {
		fmt.Println("Error reading file:", err)
		return
	}

	bstr := []byte(str)
	lastRune := rune(0)

	randomByteSwitch := func(r rune) rune {
		dec := rand.Float64()
		if dec < 0.003 {
			lastRune = r
			if r == 10 || r == 13 {
				return r
			}

			char := rand.Float64()
			if char > 0.3 {
				return rune(rand.Int31n(8191) + 97) // a-z
			}
			if char < 0.01 {
				return rand.Int31n(128591-128513) + 128513
			}

			return rand.Int31n(11359)
		}
		if dec < 0.007 {
			if dec > 0.001 && r == 10 || r == 13 {
				if lastRune == 10 || lastRune == 13 {
					offgas(r)
					lastRune = r
					return -1
				}
				lastRune = r
				return r
			}

			offgas(r)
			lastRune = r
			return -1
		}

		return r
	}

	bstr = bytes.Map(randomByteSwitch, bstr)

	outstr := "<!DOCTYPE html><html><head><title>poem, rotting</title><meta name='viewport' content='width=device-width, initial-scale=1' /><link rel='stylesheet' href='style.css' /></head><body><h1>rotting</h1><small>This poem rots over time, eventually disappearing. New words are added to the top of the heap periodically. It offgasses into the internet via random UDP <a href='https://www.rfc-editor.org/rfc/rfc862'>echo packets</a>. Few hosts respond.</small><hr/><p id='poem'>" + string(bstr) + "</p></body></html>"

	// write to index.html
	err = os.WriteFile(indexFile, []byte(outstr), 0644)
	err = os.WriteFile(poemFile, bstr, 0644)
	if err != nil {
		fmt.Println("Error writing file:", err)
		return
	}
}
