package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"

	"github.com/modelcontextprotocol/go-sdk/mcp"
	"skraak_mcp/prompts"
	"skraak_mcp/resources"
	"skraak_mcp/tools"
)

// dbPath stores the path to the DuckDB database
var dbPath string

func main() {
	// Parse command line arguments
	// os.Args[0] is the program name
	// os.Args[1] should be the database path
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s <path-to-duckdb-database>\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "Example: %s ./data/mydb.duckdb\n", os.Args[0])
		os.Exit(1)
	}

	dbPath = os.Args[1]

	// Set database path for tools package
	tools.SetDBPath(dbPath)

	// Set schema path for resources package
	schemaPath := filepath.Join(filepath.Dir(os.Args[0]), "db", "schema.sql")
	resources.SetSchemaPath(schemaPath)

	// Create MCP server with metadata
	server := mcp.NewServer(&mcp.Implementation{
		Name:    "skraak_mcp",
		Version: "v1.0.0",
	}, nil)

	// Register the get_current_time tool
	mcp.AddTool(server, &mcp.Tool{
		Name:        "get_current_time",
		Description: "Get the current system time with timezone information",
	}, tools.GetCurrentTime)

	// Register the generic SQL query tool
	mcp.AddTool(server, &mcp.Tool{
		Name:        "execute_sql",
		Description: "Execute arbitrary SQL SELECT queries against the database. Supports parameterized queries with ? placeholders. Database is read-only. Results limited to 1000 rows by default (max 10000). Use with schema resources to construct queries.",
	}, tools.ExecuteSQL)

	// Register write tools
	mcp.AddTool(server, &mcp.Tool{
		Name:        "create_dataset",
		Description: "Create a new dataset. Returns the created dataset with generated ID and timestamps.",
	}, tools.CreateDataset)

	mcp.AddTool(server, &mcp.Tool{
		Name:        "create_location",
		Description: "Create a new location within a dataset. Requires valid dataset_id, GPS coordinates, and IANA timezone.",
	}, tools.CreateLocation)

	mcp.AddTool(server, &mcp.Tool{
		Name:        "create_cluster",
		Description: "Create a new cluster within a location. Location must belong to the specified dataset.",
	}, tools.CreateCluster)

	mcp.AddTool(server, &mcp.Tool{
		Name:        "create_cyclic_recording_pattern",
		Description: "Create a reusable recording pattern with record/sleep cycle in seconds.",
	}, tools.CreateCyclicRecordingPattern)

	mcp.AddTool(server, &mcp.Tool{
		Name:        "import_audio_files",
		Description: "Batch import WAV files from a folder into the database. Automatically parses AudioMoth and filename timestamps, calculates hashes, extracts metadata, and computes astronomical data. Files are imported in a single transaction. Duplicate files (by hash) are skipped.",
	}, tools.ImportAudioFiles)

	// Register schema resources
	schemaResource, schemaTemplate := resources.GetSchemaResources()
	server.AddResource(schemaResource, resources.SchemaResourceHandler)
	server.AddResourceTemplate(schemaTemplate, resources.SchemaResourceHandler)

	// Register prompts
	server.AddPrompt(prompts.GetQueryDatasetsPrompt(), prompts.QueryDatasetsPromptHandler)
	server.AddPrompt(prompts.GetExploreSchemaPrompt(), prompts.ExploreSchemaPromptHandler)
	server.AddPrompt(prompts.GetExploreLocationHierarchyPrompt(), prompts.ExploreLocationHierarchyPromptHandler)
	server.AddPrompt(prompts.GetQueryLocationDataPrompt(), prompts.QueryLocationDataPromptHandler)
	server.AddPrompt(prompts.GetAnalyzeClusterFilesPrompt(), prompts.AnalyzeClusterFilesPromptHandler)
	server.AddPrompt(prompts.GetSystemStatusPrompt(), prompts.SystemStatusPromptHandler)

	// Run the server on stdio transport
	if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
		log.Fatalf("Server error: %v", err)
	}
}