package pkarr

import (
	

	
)

// txtRecord is a parsed TXT resource record: its owner name and concatenated
// character-strings.
type txtRecord struct {
	name string
	txt  string
}

// buildTxtPacket builds a compressed DNS reply packet containing one TXT answer
// record per value, all under name, with the given TTL. This is the
// regeneratable core that produces the DNS wire bytes the signature covers.
func buildTxtPacket( string,  []string,  uint32) ([]byte, error) {
	,  := dnsmessage.NewName(ensureFQDN())
	if  != nil {
		return nil, fmt.Errorf("invalid name %q: %w", , )
	}
	 := dnsmessage.NewBuilder(nil, dnsmessage.Header{Response: true})
	.EnableCompression()
	if  := .StartAnswers();  != nil {
		return nil, 
	}
	for ,  := range  {
		 := dnsmessage.ResourceHeader{
			Name:  ,
			Type:  dnsmessage.TypeTXT,
			Class: dnsmessage.ClassINET,
			TTL:   ,
		}
		if  := .TXTResource(, dnsmessage.TXTResource{TXT: splitTxt()});  != nil {
			return nil, 
		}
	}
	return .Finish()
}

// parsePacket parses a DNS packet and returns its TXT answer records.
func parsePacket( []byte) ([]txtRecord, error) {
	var  dnsmessage.Parser
	if ,  := .Start();  != nil {
		return nil, 
	}
	if  := .SkipAllQuestions();  != nil {
		return nil, 
	}
	var  []txtRecord
	for {
		,  := .AnswerHeader()
		if  == dnsmessage.ErrSectionDone {
			break
		}
		if  != nil {
			return nil, 
		}
		if .Type != dnsmessage.TypeTXT {
			if  := .SkipAnswer();  != nil {
				return nil, 
			}
			continue
		}
		,  := .TXTResource()
		if  != nil {
			return nil, 
		}
		 = append(, txtRecord{name: .Name.String(), txt: joinTxt(.TXT)})
	}
	return , nil
}

// splitTxt splits a value into DNS character-strings of at most 255 bytes. iroh
// values are short (UserData is capped at 245), so this is usually a single
// element, but the split keeps long values valid on the wire.
func splitTxt( string) []string {
	if len() == 0 {
		return []string{""}
	}
	var  []string
	for len() > 255 {
		 = append(, [:255])
		 = [255:]
	}
	return append(, )
}

// joinTxt concatenates the character-strings of a TXT record, matching
// simple_dns's String::try_from(TXT) used by the Rust reference.
func joinTxt( []string) string {
	if len() == 1 {
		return [0]
	}
	var  string
	for ,  := range  {
		 += 
	}
	return 
}

func ensureFQDN( string) string {
	if len() > 0 && [len()-1] == '.' {
		return 
	}
	return  + "."
}