// Package decoders contains functions for parsing template.Block to a string.
package decoders

import (
	"fmt"

	"git.max-richter.dev/max/marka/parser/matcher"
	"git.max-richter.dev/max/marka/parser/utils"
	"git.max-richter.dev/max/marka/template"
)

func ParseBlock(input string, block template.Block) (any, error) {
	switch block.Codec {
	case template.CodecText:
		return input, nil
	case template.CodecYaml:
		return Yaml(input, block)
	case template.CodecList:
		return List(input, block)
	case template.CodecHashtags:
		return Keywords(input, block)
	}
	fmt.Printf("%#v\n", block)
	return nil, fmt.Errorf("unknown codec '%s'", block.Codec)
}

func Parse(matches []matcher.Block) (any, error) {
	var result any

	for i, m := range matches {
		if m.Block.Path == "@index" {
			continue
		}

		input := m.GetContent()
		value, err := ParseBlock(input, m.Block)
		var blockIdentifier any
		blockIdentifier = m.Block.Path
		if blockIdentifier == "" {
			blockIdentifier = fmt.Sprintf("#%d", i)
		}
		if err != nil {
			return nil, fmt.Errorf("failed to parse block(%s) -> %w", blockIdentifier, err)
		}
		result = utils.SetPathValue(m.Block.Path, value, result)
	}

	return result, nil
}
