package comfunc

import (
	
	
)

// ParseEnvLineOption parse env line options
type ParseEnvLineOption struct {
	// NotInlineComments dont parse inline comments.
	//  - default: false. will parse inline comments
	NotInlineComments bool
	// SkipOnErrorLine skip error line, continue parse next line
	//  - False: return error, clear parsed map
	SkipOnErrorLine bool
}

// ParseEnvLines parse simple multiline k-v string to a string-map.
// Can use to parse simple INI or DOTENV file contents.
//
// NOTE:
//
//   - It's like INI/ENV format contents.
//   - Support comments line starts with: "#", ";", "//"
//   - Support inline comments split with: " #" eg: "name=tom # a comments"
//   - DON'T support submap parse.
func ( string,  ParseEnvLineOption) ( map[string]string,  error) {
	 := strings.Split(, "\n")
	 := len()
	if  == 0 {
		return
	}

	 := make(map[string]string, )

	for ,  := range  {
		if  = strings.TrimSpace();  == "" {
			continue
		}

		// skip comments line
		if [0] == '#' || [0] == ';' || strings.HasPrefix(, "//") {
			continue
		}

		,  := splitLineByChar(, '=', !.NotInlineComments)
		// invalid line
		if  == "" {
			if .SkipOnErrorLine {
				continue
			}
			 = nil
			 = fmt.Errorf("invalid line contents: must match `KEY=VAL`(line: %s)", )
			return
		}

		[] = 
	}

	return , nil
}

// SplitLineToKv parse string line to k-v, not support comments.
//
// Example:
//
//	'DEBUG=true' => ['DEBUG', 'true']
//
// NOTE: line must contain '=', allow: 'ENV_KEY='
func (,  string) (string, string) {
	return SplitKvBySep(, , false)
}

// SplitKvBySep parse string line to k-v, support parse comments.
//   - rmInlineComments: check and remove inline comments by ' #'
func (,  string,  bool) (,  string) {
	 := strings.Index(, )
	if  < 0 {
		return
	}

	return splitKvBySepPos(, , len(), )
}

func splitLineByChar( string,  byte,  bool) (,  string) {
	 := strings.IndexByte(, )
	if  < 0 {
		return
	}

	return splitKvBySepPos(, , 1, )
}

func splitKvBySepPos( string, ,  int,  bool) (,  string) {
	// key cannot be empty
	 = strings.TrimSpace([0:])
	if  == "" {
		return "", ""
	}
	 = strings.TrimSpace([+:])

	// check quotes if present
	if  := len();  >= 2 {
		// remove quotes
		if ([0] == '"' && [-1] == '"') || ([0] == '\'' && [-1] == '\'') {
			 = [1 : -1]
			return
		}

		if ! {
			return
		}

		// value is empty, only inline comments
		if [0] == '#' {
			 = ""
			return
		}

		// remove inline comments
		if  := strings.Index(, " #");  > 0 {
			 = strings.TrimRight([0:], " \t")
			 = len()
			// remove quotes
			if ([0] == '"' && [-1] == '"') || ([0] == '\'' && [-1] == '\'') {
				 = [1 : -1]
				return
			}
		}
	}

	return
}