package analyzer

import (
	"github.com/sirupsen/logrus"
)

// Analyzer is responsible for analyzing codebases and guessing the technology stack.

var stacks = make(map[string]Stack)

// RegisterStack registers a new technology stack for analysis.
func RegisterStack(stack Stack) {
	logrus.Debugf("Registering stack: %s", stack.Name())
	if stack == nil {
		panic("stack cannot be nil")
	}
	name := stack.Name()
	if _, exists := stacks[name]; exists {
		panic("stack already registered: " + name)
	}
	stacks[name] = stack
}

type Stack interface {
	// Name returns the name of the technology stack.
	Name() string
	// Analyze analyzes the codebase and returns a guessed technology stack.
	Analyze(codebasePath string) (bool, error)
	// GenerateDockerfile generates a Dockerfile for the technology stack.
	GenerateDockerfile(codebasePath string) (string, error)
	// Close cleans up any resources used by the stack.
}

// AnalyzeCode analyzes the provided codebase and returns a guessed technology stack.
func AnalyzeCode(codebasePath string) (Stack, error) {
	logrus.Debugf("Analyzing codebase at path: %s", codebasePath)
	logrus.Debugf("Registered stacks: %v", stacks)
	// Iterate through registered stacks and analyze the codebase
	for _, stack := range stacks {
		logrus.Debugf("Analyzing with stack: %s", stack.Name())
		if stack == nil {
			continue // Skip nil stacks
		}
		// Perform analysis
		guessed, err := stack.Analyze(codebasePath)
		if err != nil {
			return nil, err // Return error if analysis fails
		}
		if guessed {
			logrus.Infof("Guessed technology stack: %s", stack.Name())
			return stack, nil // Return the stack if analysis is successful
		}
	}

	// Placeholder implementation
	return nil, nil // Replace with actual analysis logic
}

// Close cleans up any resources used by the Analyzer.
func Close() {
	// Implement any cleanup logic if necessary
	// For example, closing connections, stopping background tasks, etc.
}
