package config

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

	"github.com/joho/godotenv"
	"gopkg.in/yaml.v3"
)

// Config represents the application configuration
type Config struct {
	Server   ServerConfig   `yaml:"server"`
	Database DatabaseConfig `yaml:"database"`
	IMAP     IMAPConfig     `yaml:"imap_defaults"`
	AI       AIConfig       `yaml:"ai"`
	Worker   WorkerConfig   `yaml:"worker"`
	Folders  FolderConfig   `yaml:"folders"`
	Logging  LoggingConfig  `yaml:"logging"`
}

// ServerConfig holds web server configuration
type ServerConfig struct {
	Port         int    `yaml:"port"`
	Host         string `yaml:"host"`
	SessionSecret string `yaml:"session_secret"`
}

// DatabaseConfig holds database configuration
type DatabaseConfig struct {
	Path       string `yaml:"path"`
	AutoMigrate bool   `yaml:"auto_migrate"`
}

// IMAPConfig holds default IMAP configuration
type IMAPConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	TLS      bool   `yaml:"tls"`
	BatchSize int    `yaml:"batch_size"`
	PollIntervalMinutes int `yaml:"poll_interval_minutes"`
}

// AIConfig holds AI classification configuration
type AIConfig struct {
	Model      string `yaml:"model"`
	MaxTokens  int    `yaml:"max_tokens"`
	Temperature float64 `yaml:"temperature"`
	PromptFile string `yaml:"prompt_file"`
}

// WorkerConfig holds background worker configuration
type WorkerConfig struct {
	SteadyStateBatchSize      int `yaml:"steady_state_batch_size"`
	SteadyStateIntervalMinutes int `yaml:"steady_state_interval_minutes"`
	CatchUpBatchSize          int `yaml:"catch_up_batch_size"`
	CatchUpCooldownSeconds    int `yaml:"catch_up_cooldown_seconds"`
}

// FolderConfig holds email folder names
type FolderConfig struct {
	Important     string `yaml:"important"`
	Ecommerce     string `yaml:"ecommerce"`
	Notifications string `yaml:"notifications"`
	Finance       string `yaml:"finance"`
	Social        string `yaml:"social"`
	Other         string `yaml:"other"`
	Spam          string `yaml:"spam"`
}

// LoggingConfig holds logging configuration
type LoggingConfig struct {
	Level       string `yaml:"level"`
	File        string `yaml:"file"`
	MaxSizeMB   int    `yaml:"max_size_mb"`
	MaxBackups  int    `yaml:"max_backups"`
	MaxAgeDays  int    `yaml:"max_age_days"`
}

// Environment variables
type Environment struct {
	DeepSeekAPIKey string
	SMTPHost       string
	SMTPPort       string
	SMTPUser       string
	SMTPPass       string
	AppSecret      string
}

// LoadConfig loads configuration from YAML file and environment variables
func LoadConfig(configPath string) (*Config, *Environment, error) {
	// Load .env file
	if err := godotenv.Load(); err != nil {
		// It's okay if .env doesn't exist in production
		fmt.Printf("Note: .env file not found: %v\n", err)
	}

	// Read YAML config
	data, err := os.ReadFile(configPath)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to read config file: %w", err)
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, nil, fmt.Errorf("failed to parse config file: %w", err)
	}

	// Load environment variables
	env := &Environment{
		DeepSeekAPIKey: os.Getenv("DEEPSEEK_API_KEY"),
		SMTPHost:       os.Getenv("SMTP_HOST"),
		SMTPPort:       os.Getenv("SMTP_PORT"),
		SMTPUser:       os.Getenv("SMTP_USER"),
		SMTPPass:       os.Getenv("SMTP_PASS"),
		AppSecret:      os.Getenv("APP_SECRET"),
	}

	// Use APP_SECRET from environment if available
	if env.AppSecret != "" {
		config.Server.SessionSecret = env.AppSecret
	}

	return &config, env, nil
}

// GetDefaultConfigPath returns the default path to config.yaml
func GetDefaultConfigPath() (string, error) {
	execPath, err := os.Executable()
	if err != nil {
		// Fallback to relative path
		return "bin/config.yaml", nil
	}
	
	execDir := filepath.Dir(execPath)
	return filepath.Join(execDir, "config.yaml"), nil
}