package engine

import "strings"

// topsqlTablePrefixes 表名前缀 → Hive 目录 component=…（必须按前缀从长到短匹配，避免歧义）
var topsqlTablePrefixes = []struct {
	prefix    string
	component string
}{
	{"topsql_plan_meta_", "component=topsql_plan_meta"},
	{"topsql_sql_meta_", "component=topsql_sql_meta"},
	{"topsql_topru_", "component=topru"},
	{"topsql_tidb_", "component=tidb"},
	{"topsql_tikv_", "component=tikv"},
}

// ResolveTopSQLDataSource 根据 TopSQL 表名追加 O11y 的 component 目录，与 Athena 使用的 S3 布局一致（OSS 同样适用）
// 例如 topsql_tidb_123456 → {base}/component=tidb/；topsql_123456（聚合表名）→ {base}/component=tidb/
func ResolveTopSQLDataSource(baseDataSource string, tableName string) string {
	base := strings.TrimRight(baseDataSource, "/")
	for _, row := range topsqlTablePrefixes {
		if strings.HasPrefix(tableName, row.prefix) {
			return base + "/" + row.component + "/"
		}
	}
	// rewrite 后的聚合表名 topsql_<clusterId>（仅数字后缀），数据落在 tidb 组件目录
	if strings.HasPrefix(tableName, "topsql_") {
		suffix := strings.TrimPrefix(tableName, "topsql_")
		if suffix != "" && isAllDecimalDigits(suffix) {
			return base + "/component=tidb/"
		}
	}
	return baseDataSource
}

func isAllDecimalDigits(s string) bool {
	for _, c := range s {
		if c < '0' || c > '9' {
			return false
		}
	}
	return s != ""
}
