package tools

import (
	"context"
	"os"
	"path/filepath"
	"testing"
)

func TestPatternIntegration_CreateClusterWithExistingPattern(t *testing.T) {
	testDB := filepath.Join("..", "db", "test.duckdb")
	if _, err := os.Stat(testDB); os.IsNotExist(err) {
		t.Skipf("Test database not found at %s", testDB)
	}
	SetDBPath(testDB)
	ctx := context.Background()

	t.Run("QueryExistingPatterns", func(t *testing.T) {
		testQueryExistingPatterns(t, ctx)
	})

	t.Run("CreateClusterWithExistingPattern", func(t *testing.T) {
		testCreateClusterWithPattern(t, ctx)
	})
}

func testQueryExistingPatterns(t *testing.T, ctx context.Context) {
	t.Helper()
	input := ExecuteSQLInput{
		Query: "SELECT id, record_s, sleep_s FROM cyclic_recording_pattern WHERE active = true ORDER BY record_s, sleep_s",
	}

	output, err := ExecuteSQL(ctx, input)
	if err != nil {
		t.Fatalf("Failed to query patterns: %v", err)
	}

	if len(output.Rows) == 0 {
		t.Fatal("Expected at least one pattern")
	}

	t.Logf("Found %d patterns", len(output.Rows))
	for i, row := range output.Rows {
		t.Logf("Pattern %d: ID=%v, record_s=%v, sleep_s=%v", i+1, row["id"], row["record_s"], row["sleep_s"])
	}
}

func testCreateClusterWithPattern(t *testing.T, ctx context.Context) {
	t.Helper()
	// Find a valid dataset
	datasetOutput, err := ExecuteSQL(ctx, ExecuteSQLInput{
		Query: "SELECT id FROM dataset WHERE active = true LIMIT 1",
	})
	if err != nil || len(datasetOutput.Rows) == 0 {
		t.Skip("No active datasets found in test database")
	}
	datasetID := datasetOutput.Rows[0]["id"].(string)

	// Find a valid location
	locationOutput, err := ExecuteSQL(ctx, ExecuteSQLInput{
		Query:      "SELECT id FROM location WHERE dataset_id = ? AND active = true LIMIT 1",
		Parameters: []any{datasetID},
	})
	if err != nil || len(locationOutput.Rows) == 0 {
		t.Skip("No active locations found in test database")
	}
	locationID := locationOutput.Rows[0]["id"].(string)

	t.Logf("Using dataset: %s, location: %s", datasetID, locationID)

	sampleRate := 16000
	output, err := CreateOrUpdateCluster(ctx, ClusterInput{
		DatasetID:                &datasetID,
		LocationID:               &locationID,
		Name:                     new("Integration Test Cluster"),
		SampleRate:               &sampleRate,
		CyclicRecordingPatternID: new("IBv_KxDGsNQs"),
	})
	if err != nil {
		t.Fatalf("Failed to create cluster: %v", err)
	}
	clusterID := output.Cluster.ID
	t.Logf("Created cluster: %s with pattern reference", clusterID)

	// Verify the cluster has the pattern reference
	sqlOutput, err := ExecuteSQL(ctx, ExecuteSQLInput{
		Query:      "SELECT c.name, c.cyclic_recording_pattern_id, p.record_s, p.sleep_s FROM cluster c LEFT JOIN cyclic_recording_pattern p ON c.cyclic_recording_pattern_id = p.id WHERE c.id = ?",
		Parameters: []any{clusterID},
	})
	if err != nil {
		t.Fatalf("Failed to verify cluster: %v", err)
	}
	if len(sqlOutput.Rows) != 1 {
		t.Fatalf("Expected 1 row, got %d", len(sqlOutput.Rows))
	}

	row := sqlOutput.Rows[0]
	t.Logf("Row data: %+v", row)

	if row["cyclic_recording_pattern_id"] != "IBv_KxDGsNQs" {
		t.Errorf("Expected pattern ID 'IBv_KxDGsNQs', got '%v'", row["cyclic_recording_pattern_id"])
	}
	if row["cyclic_recording_pattern_id"] == nil || row["cyclic_recording_pattern_id"] == "" {
		t.Error("Pattern ID is empty")
	}
	if row["record_s"] == nil {
		t.Error("record_s is nil")
	}
	if row["sleep_s"] == nil {
		t.Error("sleep_s is nil")
	}
}