package main

import (
	"encoding/json"
	"os"
	"strings"
)

type story struct {
	Places []placeBlock `json:"places"`
}

type placeBlock struct {
	Code         string        `json:"code"`
	Name         string        `json:"name"`
	Text         string        `json:"text"`
	Applications []application `json:"applications,omitempty"`
}

type application struct {
	Name string `json:"name"`
}

func main() {
	b, err := os.ReadFile("./cmd/text_to_story/text.txt")
	if err != nil {
		panic(err)
	}

	story := &story{}
	lines := strings.Split(string(b), "\n")
	var place *placeBlock
	text := ""
	for _, line := range lines {
		if strings.HasPrefix(line, "[") {
			if place != nil {
				place.Text = strings.TrimSpace(text)
				story.Places = append(story.Places, *place)
				text = ""
			}
			place = &placeBlock{}
			codeAndName := strings.Split(line, " ")
			place.Code = strings.Trim(codeAndName[0], "[]")
			place.Name = strings.TrimSpace(strings.TrimPrefix(strings.Join(codeAndName[1:], " "), "-"))
			continue
		}
		if strings.HasPrefix(line, "Приложение:") {
			place.Applications = append(
				place.Applications,
				application{
					Name: strings.TrimSpace(strings.TrimPrefix(line, "Приложение:")),
				},
			)
			continue
		}
		text += line + "\n"
	}
	place.Text = strings.TrimSpace(text)
	story.Places = append(story.Places, *place)

	res, err := json.Marshal(story)
	if err != nil {
		panic(err)
	}
	if err := os.WriteFile("./cmd/text_to_story/story.json", res, 0x777); err != nil {
		panic(err)
	}
}
