package lines

import (
	"bytes"
	"fmt"
	"log"
	"time"

	m "git.k-space.ee/k-space/logmower-shipper/pkg/mongo"
)

func (unparsed RawC) parse(parsed chan<- singleLine) {
	for {
		raw, ok := <-unparsed
		if !ok {
			close(parsed)
			return
		}

		line := singleLine{Raw: raw}

		if err := line.parse(); err != nil {
			promRecordPrefixParsingErr.WithLabelValues(raw.MetricsName).Add(1)
			log.Printf("parsing kubernetes log line in %q: %e", raw.File.Path, err)

			continue
		}

		parsed <- line
	}
}

type (
	singleLines <-chan singleLine
	singleLine  struct {
		Raw

		// populated by parse()
		m.ParsedMetadata
		partial bool // P or F
	}
)

func (line *singleLine) parse() (err error) {
	split := bytes.SplitN(line.B, []byte(" "), 4)
	if len(split) != 4 {
		return fmt.Errorf("expected at least 3 spaces in , got %d", len(split)-1)
	}

	line.TimeKubernetes, err = time.Parse(time.RFC3339Nano, string(split[0]))
	if err != nil {
		return fmt.Errorf("invalid time: %w", err)
	}

	line.StdErr = string(split[1]) == "stderr" // or stdout

	switch string(split[2]) {
	case "P":
		line.partial = true
	case "F":
	default:
		return fmt.Errorf("partial indicator must be 'P' or 'F', not %q", split[2])
	}

	line.B = split[3]
	return nil
}
