// Copyright (c) 2021 - 2025, Ludvig Lundgren and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later

//go:build generate

package main

import (
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
)

func main() {
	//migrationDir := "internal/database/migrations/sqlite"
	migrationDir := "../sqlite"
	//outputFile := "internal/database/migrations/sqlite.go"
	outputFile := "../sqlite.go"

	// Read all .sql files from the migration directory
	files, err := filepath.Glob(filepath.Join(migrationDir, "*.sql"))
	if err != nil {
		panic(fmt.Sprintf("Failed to read migration files: %v", err))
	}

	// Sort files by migration ID (numeric part before underscore)
	sort.Slice(files, func(i, j int) bool {
		idI := extractMigrationID(filepath.Base(files[i]))
		idJ := extractMigrationID(filepath.Base(files[j]))
		return idI < idJ
	})

	fmt.Printf("Found %d files\n", len(files))

	// Generate the migration entries
	var migrations []string
	for _, file := range files {
		filename := filepath.Base(file)
		name := strings.TrimSuffix(filename, ".sql")
		if name == "current_schema_sqlite" {
			continue
		}
		//migrations = append(migrations, fmt.Sprintf(`	migrate.AddMigration(&migrator.Migration{Name: "%s", File: "%s"})`, name, filename))
		migrations = append(migrations, fmt.Sprintf(`	migrate.AddFileMigration("%s")`, filename))
	}

	// Read the current file to preserve other parts
	currentContent, err := os.ReadFile(outputFile)
	if err != nil {
		panic(fmt.Sprintf("Failed to read current file: %v", err))
	}

	// Replace the section between markers
	content := string(currentContent)
	startMarker := "// Code below generated by go generate generate_migrations.go"
	endMarker := "// Code above generated by go generate generate_migrations.go"

	startIdx := strings.Index(content, startMarker)
	if startIdx == -1 {
		panic("Could not find start marker in the file")
	}

	endIdx := strings.Index(content, endMarker)
	if endIdx == -1 {
		panic("Could not find end marker in the file")
	}

	// Build new content
	newContent := content[:startIdx+len(startMarker)] + "\n" +
		strings.Join(migrations, "\n") + "\n\t" +
		content[endIdx:]

	// Write the updated file
	err = os.WriteFile(outputFile, []byte(newContent), 0644)
	if err != nil {
		panic(fmt.Sprintf("Failed to write file: %v", err))
	}

	fmt.Printf("Generated %d migrations in %s\n", len(migrations), outputFile)
}

func extractMigrationID(filename string) int {
	parts := strings.Split(filename, "_")
	if len(parts) == 0 {
		return 0
	}
	id, err := strconv.Atoi(parts[0])
	if err != nil {
		return 0
	}
	return id
}
