package virtualtables

import (
	"context"

	"github.com/everything-on-mysql/cassandra-on-mysql/pkg/cql/parser"
	"github.com/everything-on-mysql/cassandra-on-mysql/pkg/cql/tenancy"
	"github.com/everything-on-mysql/cassandra-on-mysql/pkg/cql/types"
)

// QueryOptions contains options for virtual table queries
type QueryOptions struct {
	WhereClause parser.Expression // Parsed WHERE clause
	Limit       *int64
	Offset      *int64
}

// DataProvider is a function that generates rows for a virtual table
type DataProvider func(ctx context.Context, opts QueryOptions) ([]types.Row, error)

type providerFactory func(columns []types.ColumnInfo) DataProvider

func buildRow(columns []types.ColumnInfo, values map[string]interface{}) types.Row {
	row := types.Row{Values: make([]interface{}, len(columns))}
	for i, col := range columns {
		if val, ok := values[col.Name]; ok {
			row.Values[i] = val
		}
	}
	return row
}

func buildRows(columns []types.ColumnInfo, values []map[string]interface{}) []types.Row {
	rows := make([]types.Row, 0, len(values))
	for _, row := range values {
		rows = append(rows, buildRow(columns, row))
	}
	return rows
}

func provideEmpty(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	return []types.Row{}, nil
}

func (r *Registry) providerFactories() map[string]providerFactory {
	return map[string]providerFactory{
		"system_views.clients":           provideClients,
		"system_views.settings":          provideSettings,
		"system_views.thread_pools":      provideThreadPools,
		"system_views.system_properties": provideSystemProperties,
		"system_views.system_logs":       provideSystemLogs,
	}
}

// provideClients returns active client connections
func provideClients(columns []types.ColumnInfo) DataProvider {
	return func(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
		_ = opts
		provider, ok := clientInfoProviderFromContext(ctx)
		if !ok {
			return []types.Row{}, nil
		}
		tenantID := tenancy.TenantIDFromContext(ctx)
		clients := provider()
		rows := make([]types.Row, 0, len(clients))
		for _, info := range clients {
			if tenantID != "" && info.TenantID != tenantID {
				continue
			}
			stage := "ready"
			if info.Username == "" {
				stage = "connecting"
			}
			var sslProtocol interface{}
			if info.SSLProtocol != "" {
				sslProtocol = info.SSLProtocol
			}
			var sslCipherSuite interface{}
			if info.SSLCipherSuite != "" {
				sslCipherSuite = info.SSLCipherSuite
			}
			rows = append(rows, buildRow(columns, map[string]interface{}{
				"address":                 info.Address,
				"port":                    int32(info.Port),
				"hostname":                info.Hostname,
				"username":                info.Username,
				"connection_stage":        stage,
				"protocol_version":        int32(info.ProtocolVersion),
				"client_options":          info.ClientOptions,
				"driver_name":             info.DriverName,
				"driver_version":          info.DriverVersion,
				"request_count":           info.RequestCount,
				"ssl_enabled":             info.SSLEnabled,
				"ssl_protocol":            sslProtocol,
				"ssl_cipher_suite":        sslCipherSuite,
				"keyspace_name":           info.Keyspace,
				"authentication_mode":     nil,
				"authentication_metadata": nil,
			}))
		}
		return rows, nil
	}
}

// provideSettings returns configuration settings
func provideSettings(columns []types.ColumnInfo) DataProvider {
	return func(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
		_ = ctx
		_ = opts
		return []types.Row{}, nil
	}
}

// provideThreadPools returns thread pool metrics
func provideThreadPools(columns []types.ColumnInfo) DataProvider {
	return func(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
		_ = ctx
		_ = opts
		// Mock thread pool data
		threadPools := []struct {
			name                string
			activeTasks         int64
			activeTasksLimit    int64
			blockedTasks        int64
			blockedTasksAllTime int64
			completedTasks      int64
			pendingTasks        int64
		}{
			{"AntiEntropyStage", 0, 1, 0, 0, 0, 0},
			{"CacheCleanupExecutor", 0, 1, 0, 0, 0, 0},
			{"CompactionExecutor", 0, 2, 0, 0, 881, 0},
			{"CounterMutationStage", 0, 32, 0, 0, 0, 0},
			{"GossipStage", 0, 1, 0, 0, 0, 0},
			{"HintsDispatcher", 0, 2, 0, 0, 0, 0},
			{"InternalResponseStage", 0, 2, 0, 0, 0, 0},
			{"MemtableFlushWriter", 0, 2, 0, 0, 1, 0},
			{"MemtablePostFlush", 0, 1, 0, 0, 2, 0},
			{"MemtableReclaimMemory", 0, 1, 0, 0, 1, 0},
			{"MigrationStage", 0, 1, 0, 0, 0, 0},
			{"MiscStage", 0, 1, 0, 0, 0, 0},
			{"MutationStage", 0, 32, 0, 0, 0, 0},
			{"Native-Transport-Requests", 1, 128, 0, 0, 130, 0},
			{"PendingRangeCalculator", 0, 1, 0, 0, 1, 0},
			{"PerDiskMemtableFlushWriter_0", 0, 2, 0, 0, 1, 0},
			{"ReadStage", 0, 32, 0, 0, 13, 0},
			{"Repair-Task", 0, 2147483647, 0, 0, 0, 0},
			{"RequestResponseStage", 0, 2, 0, 0, 0, 0},
			{"Sampler", 0, 1, 0, 0, 0, 0},
			{"SecondaryIndexManagement", 0, 1, 0, 0, 0, 0},
			{"ValidationExecutor", 0, 2147483647, 0, 0, 0, 0},
			{"ViewBuildExecutor", 0, 1, 0, 0, 0, 0},
			{"ViewMutationStage", 0, 32, 0, 0, 0, 0},
		}

		rowValues := make([]map[string]interface{}, 0, len(threadPools))
		for _, tp := range threadPools {
			rowValues = append(rowValues, map[string]interface{}{
				"name":                   tp.name,
				"active_tasks":           tp.activeTasks,
				"active_tasks_limit":     tp.activeTasksLimit,
				"blocked_tasks":          tp.blockedTasks,
				"blocked_tasks_all_time": tp.blockedTasksAllTime,
				"completed_tasks":        tp.completedTasks,
				"pending_tasks":          tp.pendingTasks,
			})
		}

		return buildRows(columns, rowValues), nil
	}
}

// provideLocalReadLatency returns local read latency metrics
func provideLocalReadLatency(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock latency data
	data := []struct {
		keyspace string
		table    string
		p50      float64
		p99      float64
		count    int64
		max      float64
		perSec   float64
	}{
		{"keyspace1", "standard1", 0.043, 0.152, 49785158, 186.563, 11418.356},
		{"keyspace2", "users", 0.021, 0.089, 12345678, 98.234, 5432.123},
		{"system_views", "clients", 0.005, 0.012, 123456, 5.432, 123.456},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.p50,
				d.p99,
				d.count,
				d.max,
				d.perSec,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.local_read_latency"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideLocalWriteLatency returns local write latency metrics
func provideLocalWriteLatency(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock latency data
	data := []struct {
		keyspace string
		table    string
		p50      float64
		p99      float64
		count    int64
		max      float64
		perSec   float64
	}{
		{"keyspace1", "standard1", 0.051, 0.178, 34567890, 210.456, 8923.456},
		{"keyspace2", "users", 0.028, 0.095, 9876543, 110.234, 4321.987},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.p50,
				d.p99,
				d.count,
				d.max,
				d.perSec,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.local_write_latency"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideDiskUsage returns disk usage by table
func provideDiskUsage(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	_ = ctx
	_ = opts
	return []types.Row{}, nil
}

// provideCaches returns cache statistics
func provideCaches(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock cache data
	caches := []struct {
		name                       string
		capacityBytes              int64
		entryCount                 int64
		hitCount                   int64
		hitRatio                   float64
		recentHitRatePerSecond     float64
		recentRequestRatePerSecond float64
		requestCount               int64
		sizeBytes                  int64
	}{
		{"chunks", 229638144, 29, 166, 0.83, 5.0, 6.0, 200, 475136},
		{"counters", 26214400, 0, 0, 0.0, 0.0, 0.0, 0, 0},
		{"keys", 52428800, 14, 124, 0.873239, 4.0, 4.0, 142, 1248},
		{"rows", 0, 0, 0, 0.0, 0.0, 0.0, 0, 0},
	}

	rows := make([]types.Row, 0, len(caches))
	for _, c := range caches {
		rows = append(rows, types.Row{
			Values: []interface{}{
				c.name,
				c.capacityBytes,
				c.entryCount,
				c.hitCount,
				c.hitRatio,
				c.recentHitRatePerSecond,
				c.recentRequestRatePerSecond,
				c.requestCount,
				c.sizeBytes,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.caches"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideSSTableTasks returns SSTable task progress
func provideSSTableTasks(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	_ = ctx
	_ = opts
	return []types.Row{}, nil
}

// provideSystemProperties returns system properties
func provideSystemProperties(columns []types.ColumnInfo) DataProvider {
	return func(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
		_ = ctx
		_ = opts
		return []types.Row{}, nil
	}
}

// provideCoordinatorReadLatency returns coordinator read latency metrics
func provideCoordinatorReadLatency(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock coordinator read data
	data := []struct {
		keyspace string
		table    string
		p50      float64
		p99      float64
		count    int64
		max      float64
		perSec   float64
	}{
		{"keyspace1", "standard1", 0.065, 0.234, 51234567, 245.678, 12543.234},
		{"keyspace2", "users", 0.032, 0.112, 15432109, 123.456, 6543.210},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.p50,
				d.p99,
				d.count,
				d.max,
				d.perSec,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.coordinator_read_latency"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideCoordinatorWriteLatency returns coordinator write latency metrics
func provideCoordinatorWriteLatency(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock coordinator write data
	data := []struct {
		keyspace string
		table    string
		p50      float64
		p99      float64
		count    int64
		max      float64
		perSec   float64
	}{
		{"keyspace1", "standard1", 0.078, 0.256, 39876543, 267.890, 9876.543},
		{"keyspace2", "users", 0.041, 0.134, 12345678, 134.567, 5432.109},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.p50,
				d.p99,
				d.count,
				d.max,
				d.perSec,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.coordinator_write_latency"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideInternodeInbound returns internode inbound messaging metrics
func provideInternodeInbound(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock internode inbound data (typically empty in single-node setup)
	rows := []types.Row{}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.internode_inbound"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideInternodeOutbound returns internode outbound messaging metrics
func provideInternodeOutbound(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock internode outbound data (typically empty in single-node setup)
	rows := []types.Row{}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.internode_outbound"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideMaxPartitionSize returns maximum partition size metrics
func provideMaxPartitionSize(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock max partition size data
	data := []struct {
		keyspace string
		table    string
		max      int64
	}{
		{"keyspace1", "standard1", 1048576},
		{"keyspace2", "users", 524288},
		{"tlp_stress", "keyvalue", 2097152},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.max,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.max_partition_size"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideRowsPerRead returns rows per read metrics
func provideRowsPerRead(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock rows per read data
	data := []struct {
		keyspace string
		table    string
		max      int64
		median   float64
	}{
		{"keyspace1", "standard1", 150, 2.5},
		{"keyspace2", "users", 75, 1.8},
		{"tlp_stress", "keyvalue", 500, 5.2},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.max,
				d.median,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.rows_per_read"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideTombstonesPerRead returns tombstone metrics
func provideTombstonesPerRead(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock tombstone data
	data := []struct {
		keyspace string
		table    string
		max      int64
		median   float64
	}{
		{"keyspace1", "standard1", 120, 3.2},
		{"keyspace2", "users", 45, 1.5},
		{"tlp_stress", "keyvalue", 200, 8.7},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.max,
				d.median,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.tombstones_per_read"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideLocalScan returns local scan metrics
func provideLocalScan(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock local scan data
	data := []struct {
		keyspace string
		table    string
		p50      float64
		p99      float64
		count    int64
		max      float64
		perSec   float64
	}{
		{"keyspace1", "standard1", 0.123, 0.567, 1234567, 890.123, 234.567},
		{"keyspace2", "users", 0.089, 0.345, 987654, 456.789, 123.456},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.p50,
				d.p99,
				d.count,
				d.max,
				d.perSec,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.local_scan"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideCoordinatorScan returns coordinator scan metrics
func provideCoordinatorScan(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock coordinator scan data
	data := []struct {
		keyspace string
		table    string
		p50      float64
		p99      float64
		count    int64
		max      float64
		perSec   float64
	}{
		{"keyspace1", "standard1", 0.156, 0.678, 2345678, 987.654, 456.789},
		{"keyspace2", "users", 0.112, 0.456, 1234567, 567.890, 234.567},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.keyspace,
				d.table,
				d.p50,
				d.p99,
				d.count,
				d.max,
				d.perSec,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.coordinator_scan"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideCIDRFilteringMetricsCounts returns CIDR filtering count metrics
func provideCIDRFilteringMetricsCounts(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock CIDR filtering count data
	data := []struct {
		name  string
		value int64
	}{
		{"CIDR groups cache reload count", 2},
		{"Number of CIDR accesses accepted from CIDR group - aws", 15},
		{"Number of CIDR accesses accepted from CIDR group - gcp", 30},
		{"Number of CIDR accesses rejected from CIDR group - gcp", 6},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{d.name, d.value},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.cidr_filtering_metrics_counts"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideCIDRFilteringMetricsLatencies returns CIDR filtering latency metrics
func provideCIDRFilteringMetricsLatencies(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
	// Mock CIDR filtering latency data
	data := []struct {
		name   string
		max    int64
		p50th  int64
		p95th  int64
		p999th int64
		p99th  int64
	}{
		{"CIDR checks latency (ns)", 24601, 1, 11864, 24601, 24601},
		{"CIDR groups cache reload latency (ns)", 42510, 42510, 42510, 42510, 42510},
		{"Lookup IP in CIDR groups cache latency (ns)", 1, 1, 1, 1, 1},
	}

	rows := make([]types.Row, 0, len(data))
	for _, d := range data {
		rows = append(rows, types.Row{
			Values: []interface{}{
				d.name,
				d.max,
				d.p50th,
				d.p95th,
				d.p999th,
				d.p99th,
			},
		})
	}

	// Apply WHERE filtering
	if opts.WhereClause != nil {
		filter := NewFilterEngine(opts.WhereClause)
		filtered := make([]types.Row, 0)
		for _, row := range rows {
			match, err := filter.Evaluate(row, getVirtualTableColumns("system_views.cidr_filtering_metrics_latencies"))
			if err == nil && match {
				filtered = append(filtered, row)
			}
		}
		rows = filtered
	}

	// Apply LIMIT
	if opts.Limit != nil && int64(len(rows)) > *opts.Limit {
		rows = rows[:*opts.Limit]
	}

	return rows, nil
}

// provideSystemLogs returns system logs (if configured)
func provideSystemLogs(columns []types.ColumnInfo) DataProvider {
	return func(ctx context.Context, opts QueryOptions) ([]types.Row, error) {
		_ = ctx
		_ = opts
		return []types.Row{}, nil
	}
}

// getVirtualTableColumns returns the column definitions for a given virtual table
// This is used by the filter engine to properly evaluate WHERE clauses
func getVirtualTableColumns(tableName string) []types.ColumnInfo {
	// Look up the table in the registry to get its column definitions
	registry := NewRegistry()
	vt, ok := registry.Lookup(tableName)
	if !ok {
		return []types.ColumnInfo{}
	}
	return vt.Columns
}
