package query

import (
	"fmt"
	"strings"
)

func parseS3URI(uri string) (bucket, key string, err error) {
	uri = strings.TrimSpace(uri)
	if !strings.HasPrefix(uri, "s3://") {
		return "", "", fmt.Errorf("invalid s3 uri: %s", uri)
	}
	rest := strings.TrimPrefix(uri, "s3://")
	idx := strings.IndexByte(rest, '/')
	if idx <= 0 || idx == len(rest)-1 {
		return "", "", fmt.Errorf("invalid s3 uri: %s", uri)
	}
	return rest[:idx], rest[idx+1:], nil
}

// resolveAthenaCSVLocation maps Athena ResultConfiguration.OutputLocation + execution id
// to the CSV object Athena writes for SELECT results.
func resolveAthenaCSVLocation(outputLocation, executionID string) string {
	loc := strings.TrimSpace(outputLocation)
	if loc == "" || executionID == "" {
		return ""
	}
	lower := strings.ToLower(loc)
	if strings.HasSuffix(lower, ".csv") {
		return loc
	}
	if !strings.HasSuffix(loc, "/") {
		loc += "/"
	}
	return loc + executionID + ".csv"
}
