package main

import (
	"errors"
	"os"
	"path/filepath"
	"strings"

	"github.com/pelletier/go-toml/v2"
)

func loadConfig(path string) (Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return Config{}, err
	}

	var config Config
	if err := toml.Unmarshal(data, &config); err != nil {
		return Config{}, err
	}

	applyConfigDefaults(&config)
	if config.Volcengine.BaseURL == "" || config.Volcengine.APIKey == "" || config.Volcengine.Model == "" {
		return Config{}, errors.New("missing volcengine base_url/api_key/model in config.toml")
	}

	appDataDir, err := expandPath(config.Agent.AppDataDir)
	if err != nil {
		return Config{}, err
	}
	config.Agent.AppDataDir = appDataDir

	return config, nil
}

func applyConfigDefaults(config *Config) {
	if config.Agent.AppDataDir == "" {
		config.Agent.AppDataDir = "~/Library/Application Support/com.tauri.dev"
	}
	if config.Agent.RegionsPath == "" {
		config.Agent.RegionsPath = "data/regions/wechat.json"
	}
	if config.Agent.ScreenshotPath == "" {
		config.Agent.ScreenshotPath = "data/screenshots/WeChat.jpg"
	}
	if config.Agent.TaskOutputPath == "" {
		config.Agent.TaskOutputPath = "data/tasks/latest_task.json"
	}
	if config.Agent.TaskHistoryDir == "" {
		config.Agent.TaskHistoryDir = "data/tasks/history"
	}
	if config.Agent.ObserveMode == "" {
		config.Agent.ObserveMode = "normal"
	}
	if config.Agent.MaxScrolls <= 0 {
		config.Agent.MaxScrolls = 1
	}
	if config.Agent.ScrollDeltaY == 0 {
		config.Agent.ScrollDeltaY = 6
	}
	if config.Agent.ChatRecordsPath == "" {
		config.Agent.ChatRecordsPath = "data/chats/wechat_chat_records.json"
	}
	if config.Agent.ChatSyncMaxPages <= 0 {
		config.Agent.ChatSyncMaxPages = 3
	}
	if config.Agent.ChatSyncTopScrolls <= 0 {
		config.Agent.ChatSyncTopScrolls = 8
	}
	config.Agent.DryRun = true
}

func expandPath(path string) (string, error) {
	if path == "" {
		return "", nil
	}

	if path == "~" || strings.HasPrefix(path, "~/") {
		home, err := os.UserHomeDir()
		if err != nil {
			return "", err
		}
		if path == "~" {
			return home, nil
		}
		return filepath.Join(home, path[2:]), nil
	}

	return path, nil
}

func appDataPath(config Config, relativePath string) string {
	if filepath.IsAbs(relativePath) {
		return relativePath
	}
	return filepath.Join(config.Agent.AppDataDir, relativePath)
}
