package autoconfig

import (
	"context"
	"net/mail"
	"strings"
	"time"
)

// Discover resolves likely IMAP/SMTP settings for an email address.
func Discover(ctx context.Context, email string) (Result, error) {
	email = strings.TrimSpace(email)
	parsed, err := mail.ParseAddress(email)
	if err != nil || parsed.Address == "" {
		return Result{}, ErrInvalidEmail
	}
	email = strings.ToLower(parsed.Address)
	at := strings.LastIndex(email, "@")
	if at <= 0 || at >= len(email)-1 {
		return Result{}, ErrInvalidEmail
	}
	domain := strings.ToLower(email[at+1:])

	ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
	defer cancel()

	if preset, ok := matchDomain(domain); ok {
		r := preset.toResult(email, domain, "preset", "high")
		return r, nil
	}

	if r, ok := discoverFromMX(ctx, email, domain); ok && r.IMAPHost != "" {
		r.Email = email
		return r, nil
	}

	if r, ok := fetchMozillaAutoconfig(ctx, domain); ok {
		r.Email = email
		r.Domain = domain
		if r.IMAPHost != "" || r.SMTPHost != "" {
			return r, nil
		}
	}

	return guessFromDomain(email, domain), nil
}

func guessFromDomain(email, domain string) Result {
	return Result{
		Email:        email,
		Domain:       domain,
		ProviderID:   "custom",
		ProviderName: "Serveur personnalisé",
		Source:       "guess",
		Confidence:   "low",
		IMAPHost:     "imap." + domain,
		IMAPPort:     993,
		IMAPTLS:      true,
		SMTPHost:     "smtp." + domain,
		SMTPPort:     587,
		SMTPTLS:      true,
		UsernameHint: "email",
		AuthMethods:  []string{"password"},
		Notes: []string{
			"Aucune configuration connue pour ce domaine.",
			"Vérifiez les paramètres auprès de votre hébergeur ou activez les réglages avancés.",
		},
	}
}
