package config

import (
	"github.com/rs/zerolog/log"
	"github.com/spf13/viper"
)

// LaunchpadConfig is the top-level configuration structure for the launchpad.
type LaunchpadConfig struct {
	Variables struct {
		Required []string
	}
	Networks map[string]interface{}
	Services []Service
}

// Service defines a single service that can be managed by the launchpad.
type Service struct {
	Name string
	Type string
	Path string
	Dev  struct {
		Command      string
		Image        string
		ExposePorts  []int `mapstructure:"expose_ports"` // Ports to check for health in dev mode
		Healthcheck Healthcheck
	}
	Prod struct {
		Image        string
		Command      interface{}
		Dockerfile   string
		BuildContext string                              `mapstructure:"build_context"`
		Ports        []string
		Expose       []string
		Environment  []string
		Volumes      []string
		DependsOn    map[string]Dependency `mapstructure:"depends_on"`
		Networks     []string
		Healthcheck  Healthcheck
	}
}

// Healthcheck defines a health check for a service.
type Healthcheck struct {
	Test     []string `yaml:"test,omitempty"`
	Interval string   `yaml:"interval,omitempty"`
	Timeout  string   `yaml:"timeout,omitempty"`
	Retries  int      `yaml:"retries,omitempty"`
	// For dev mode TCP checks
	TcpPorts []int `mapstructure:"tcp_ports"`
	Path     string
}

// Dependency defines a dependency condition for docker-compose.
type Dependency struct {
	Condition string `yaml:"condition"`
}


// Load reads and parses the launchpad.toml file from the project root.
func Load() LaunchpadConfig {
	v := viper.New()
	v.SetConfigName("launchpad")
	v.AddConfigPath(".")
	v.SetConfigType("toml")

	if err := v.ReadInConfig(); err != nil {
		log.Fatal().Err(err).Msg("Failed to read launchpad.toml")
	}

	var config LaunchpadConfig
	if err := v.Unmarshal(&config); err != nil {
		log.Fatal().Err(err).Msg("Failed to parse launchpad.toml")
	}
	return config
}
