package tools

import (
	"context"
	"fmt"

	"skraak_mcp/db"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

// CreateCyclicRecordingPatternInput defines the input parameters for the create_cyclic_recording_pattern tool
type CreateCyclicRecordingPatternInput struct {
	RecordSeconds int `json:"record_seconds" jsonschema:"required,Number of seconds to record (must be positive)"`
	SleepSeconds  int `json:"sleep_seconds" jsonschema:"required,Number of seconds to sleep between recordings (must be positive)"`
}

// CreateCyclicRecordingPatternOutput defines the output structure
type CreateCyclicRecordingPatternOutput struct {
	Pattern db.CyclicRecordingPattern `json:"pattern" jsonschema:"The created recording pattern with generated ID and timestamps"`
	Message string                    `json:"message" jsonschema:"Success message"`
}

// CreateCyclicRecordingPattern implements the create_cyclic_recording_pattern tool handler
// Creates a new cyclic recording pattern with record/sleep cycle in seconds
func CreateCyclicRecordingPattern(
	ctx context.Context,
	req *mcp.CallToolRequest,
	input CreateCyclicRecordingPatternInput,
) (*mcp.CallToolResult, CreateCyclicRecordingPatternOutput, error) {
	var output CreateCyclicRecordingPatternOutput

	// Validate inputs
	if input.RecordSeconds <= 0 {
		return nil, output, fmt.Errorf("record_seconds must be positive (got %d)", input.RecordSeconds)
	}
	if input.SleepSeconds <= 0 {
		return nil, output, fmt.Errorf("sleep_seconds must be positive (got %d)", input.SleepSeconds)
	}

	// Open writable database connection
	database, err := db.OpenWriteableDB(dbPath)
	if err != nil {
		return nil, output, fmt.Errorf("database connection failed: %w", err)
	}
	defer database.Close()

	// Begin transaction
	tx, err := database.BeginTx(ctx, nil)
	if err != nil {
		return nil, output, fmt.Errorf("failed to begin transaction: %w", err)
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		}
	}()

	// Generate ID
	id, err := db.GenerateID()
	if err != nil {
		return nil, output, fmt.Errorf("failed to generate ID: %w", err)
	}

	// Insert pattern (explicitly set timestamps and active for schema compatibility)
	_, err = tx.ExecContext(ctx,
		"INSERT INTO cyclic_recording_pattern (id, record_s, sleep_s, created_at, last_modified, active) VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, TRUE)",
		id, input.RecordSeconds, input.SleepSeconds,
	)
	if err != nil {
		return nil, output, fmt.Errorf("failed to create pattern: %w", err)
	}

	// Fetch the created pattern (gets DB-generated timestamps and defaults)
	var pattern db.CyclicRecordingPattern
	err = tx.QueryRowContext(ctx,
		"SELECT id, record_s, sleep_s, created_at, last_modified, active FROM cyclic_recording_pattern WHERE id = ?",
		id,
	).Scan(&pattern.ID, &pattern.RecordS, &pattern.SleepS, &pattern.CreatedAt, &pattern.LastModified, &pattern.Active)
	if err != nil {
		return nil, output, fmt.Errorf("failed to fetch created pattern: %w", err)
	}

	// Commit transaction
	if err = tx.Commit(); err != nil {
		return nil, output, fmt.Errorf("failed to commit transaction: %w", err)
	}

	output.Pattern = pattern
	output.Message = fmt.Sprintf("Successfully created cyclic recording pattern with ID %s (record %ds, sleep %ds)",
		pattern.ID, pattern.RecordS, pattern.SleepS)

	return &mcp.CallToolResult{}, output, nil
}