main.go

   1package main
   2
   3import (
   4	"archive/tar"
   5	"bytes"
   6	"compress/gzip"
   7	"encoding/base64"
   8	"encoding/json"
   9	"fmt"
  10	"io"
  11	"log"
  12	"net/http"
  13	"os"
  14	"os/exec"
  15	"path/filepath"
  16	"regexp"
  17	"runtime"
  18	"strings"
  19	"sync"
  20	"time"
  21
  22	tea "github.com/charmbracelet/bubbletea"
  23	"github.com/floatpane/matcha/config"
  24	"github.com/floatpane/matcha/fetcher"
  25	"github.com/floatpane/matcha/sender"
  26	"github.com/floatpane/matcha/tui"
  27	"github.com/google/uuid"
  28	"github.com/yuin/goldmark"
  29	"github.com/yuin/goldmark/renderer/html"
  30)
  31
  32const (
  33	initialEmailLimit = 20
  34	paginationLimit   = 20
  35	maxCacheEmails    = 100
  36)
  37
  38// Version variables are injected by the build (GoReleaser ldflags).
  39// They default to "dev" when not set by the build system.
  40var (
  41	version = "dev"
  42	commit  = ""
  43	date    = ""
  44)
  45
  46// UpdateAvailableMsg is sent into the TUI when a newer release is detected.
  47type UpdateAvailableMsg struct {
  48	Latest  string
  49	Current string
  50}
  51
  52// internal struct for parsing GitHub release JSON.
  53type githubRelease struct {
  54	TagName string `json:"tag_name"`
  55	Assets  []struct {
  56		Name               string `json:"name"`
  57		BrowserDownloadURL string `json:"browser_download_url"`
  58	} `json:"assets"`
  59}
  60
  61type mainModel struct {
  62	current       tea.Model
  63	previousModel tea.Model
  64	config        *config.Config
  65	emails        []fetcher.Email
  66	emailsByAcct  map[string][]fetcher.Email
  67	sentEmails    []fetcher.Email
  68	sentByAcct    map[string][]fetcher.Email
  69	trashEmails   []fetcher.Email
  70	trashByAcct   map[string][]fetcher.Email
  71	archiveEmails []fetcher.Email
  72	archiveByAcct map[string][]fetcher.Email
  73	inbox         *tui.Inbox
  74	sentInbox     *tui.Inbox
  75	trashArchive  *tui.TrashArchive
  76	width         int
  77	height        int
  78	err           error
  79}
  80
  81func newInitialModel(cfg *config.Config) *mainModel {
  82	initialModel := &mainModel{
  83		emailsByAcct:  make(map[string][]fetcher.Email),
  84		sentByAcct:    make(map[string][]fetcher.Email),
  85		trashByAcct:   make(map[string][]fetcher.Email),
  86		archiveByAcct: make(map[string][]fetcher.Email),
  87	}
  88
  89	if cfg == nil || !cfg.HasAccounts() {
  90		initialModel.current = tui.NewLogin()
  91	} else {
  92		initialModel.current = tui.NewChoice()
  93		initialModel.config = cfg
  94	}
  95	return initialModel
  96}
  97
  98func (m *mainModel) Init() tea.Cmd {
  99	return tea.Batch(m.current.Init(), checkForUpdatesCmd())
 100}
 101
 102func (m *mainModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 103	var cmd tea.Cmd
 104	var cmds []tea.Cmd
 105
 106	m.current, cmd = m.current.Update(msg)
 107	cmds = append(cmds, cmd)
 108
 109	switch msg := msg.(type) {
 110	case tea.WindowSizeMsg:
 111		m.width = msg.Width
 112		m.height = msg.Height
 113		return m, nil
 114
 115	case tea.KeyMsg:
 116		if msg.String() == "ctrl+c" {
 117			return m, tea.Quit
 118		}
 119		if msg.String() == "esc" {
 120			switch m.current.(type) {
 121			case *tui.FilePicker:
 122				return m, func() tea.Msg { return tui.CancelFilePickerMsg{} }
 123			case *tui.Inbox, *tui.Login, *tui.TrashArchive:
 124				m.current = tui.NewChoice()
 125				return m, m.current.Init()
 126			}
 127		}
 128
 129	case tui.BackToInboxMsg:
 130		if m.inbox != nil {
 131			m.current = m.inbox
 132		} else {
 133			m.current = tui.NewChoice()
 134		}
 135		return m, nil
 136
 137	case tui.BackToMailboxMsg:
 138		switch msg.Mailbox {
 139		case tui.MailboxSent:
 140			if m.sentInbox != nil {
 141				m.current = m.sentInbox
 142				return m, nil
 143			}
 144		case tui.MailboxInbox:
 145			if m.inbox != nil {
 146				m.current = m.inbox
 147				return m, nil
 148			}
 149		case tui.MailboxTrash, tui.MailboxArchive:
 150			if m.trashArchive != nil {
 151				m.current = m.trashArchive
 152				return m, nil
 153			}
 154		}
 155		m.current = tui.NewChoice()
 156		return m, nil
 157
 158	case tui.DiscardDraftMsg:
 159		// Save draft to disk
 160		if msg.ComposerState != nil {
 161			draft := msg.ComposerState.ToDraft()
 162			go func() {
 163				if err := config.SaveDraft(draft); err != nil {
 164					log.Printf("Error saving draft: %v", err)
 165				}
 166			}()
 167		}
 168		m.current = tui.NewChoice()
 169		return m, m.current.Init()
 170
 171	case tui.Credentials:
 172		// Add new account or update existing
 173		account := config.Account{
 174			ID:              uuid.New().String(),
 175			Name:            msg.Name,
 176			Email:           msg.Host, // login/email used for authentication comes from Host field in the form
 177			Password:        msg.Password,
 178			ServiceProvider: msg.Provider,
 179			FetchEmail:      msg.FetchEmail,
 180		}
 181
 182		if msg.Provider == "custom" {
 183			account.IMAPServer = msg.IMAPServer
 184			account.IMAPPort = msg.IMAPPort
 185			account.SMTPServer = msg.SMTPServer
 186			account.SMTPPort = msg.SMTPPort
 187		}
 188
 189		// Ensure FetchEmail defaults to the login Email (Host) if not explicitly set
 190		if account.FetchEmail == "" && account.Email != "" {
 191			account.FetchEmail = account.Email
 192		}
 193
 194		if m.config == nil {
 195			m.config = &config.Config{}
 196		}
 197
 198		// Check if we're editing an existing account
 199		if login, ok := m.current.(*tui.Login); ok && login.IsEditMode() {
 200			// Find and update the existing account
 201			existingID := login.GetAccountID()
 202			for i, acc := range m.config.Accounts {
 203				if acc.ID == existingID {
 204					account.ID = existingID
 205					m.config.Accounts[i] = account
 206					break
 207				}
 208			}
 209		} else {
 210			m.config.AddAccount(account)
 211		}
 212
 213		if err := config.SaveConfig(m.config); err != nil {
 214			log.Printf("could not save config: %v", err)
 215			return m, tea.Quit
 216		}
 217
 218		m.current = tui.NewChoice()
 219		return m, m.current.Init()
 220
 221	case tui.GoToInboxMsg:
 222		if m.config == nil || !m.config.HasAccounts() {
 223			m.current = tui.NewLogin()
 224			return m, m.current.Init()
 225		}
 226		// Try to load from cache first for instant display
 227		if config.HasEmailCache() {
 228			return m, loadCachedEmails()
 229		}
 230		// No cache, fetch normally
 231		m.current = tui.NewStatus("Fetching emails from all accounts...")
 232		return m, tea.Batch(m.current.Init(), fetchAllAccountsEmails(m.config, tui.MailboxInbox))
 233
 234	case tui.GoToSentInboxMsg:
 235		if m.config == nil || !m.config.HasAccounts() {
 236			m.current = tui.NewLogin()
 237			return m, m.current.Init()
 238		}
 239		m.current = tui.NewStatus("Fetching sent emails from all accounts...")
 240		return m, tea.Batch(m.current.Init(), fetchAllAccountsEmails(m.config, tui.MailboxSent))
 241
 242	case tui.GoToTrashArchiveMsg:
 243		if m.config == nil || !m.config.HasAccounts() {
 244			m.current = tui.NewLogin()
 245			return m, m.current.Init()
 246		}
 247		m.current = tui.NewStatus("Fetching trash and archive emails...")
 248		return m, tea.Batch(
 249			m.current.Init(),
 250			fetchAllAccountsEmails(m.config, tui.MailboxTrash),
 251			fetchAllAccountsEmails(m.config, tui.MailboxArchive),
 252		)
 253
 254	case tui.CachedEmailsLoadedMsg:
 255		if msg.Cache == nil {
 256			// Cache load failed, fetch normally
 257			m.current = tui.NewStatus("Fetching emails from all accounts...")
 258			return m, tea.Batch(m.current.Init(), fetchAllAccountsEmails(m.config, tui.MailboxInbox))
 259		}
 260
 261		// Convert cached emails to fetcher.Email
 262		var cachedEmails []fetcher.Email
 263		emailsByAcct := make(map[string][]fetcher.Email)
 264		for _, cached := range msg.Cache.Emails {
 265			email := fetcher.Email{
 266				UID:       cached.UID,
 267				From:      cached.From,
 268				To:        cached.To,
 269				Subject:   cached.Subject,
 270				Date:      cached.Date,
 271				MessageID: cached.MessageID,
 272				AccountID: cached.AccountID,
 273			}
 274			cachedEmails = append(cachedEmails, email)
 275			emailsByAcct[cached.AccountID] = append(emailsByAcct[cached.AccountID], email)
 276		}
 277
 278		m.emails = cachedEmails
 279		m.emailsByAcct = emailsByAcct
 280		m.inbox = tui.NewInbox(m.emails, m.config.Accounts)
 281		m.current = m.inbox
 282		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 283
 284		counts := make(map[string]int)
 285		for k, v := range emailsByAcct {
 286			counts[k] = len(v)
 287		}
 288
 289		// Start background refresh
 290		return m, tea.Batch(
 291			m.current.Init(),
 292			func() tea.Msg { return tui.RefreshingEmailsMsg{Mailbox: tui.MailboxInbox} },
 293			refreshEmails(m.config, tui.MailboxInbox, counts),
 294		)
 295
 296	case tui.RequestRefreshMsg:
 297		return m, tea.Batch(
 298			func() tea.Msg { return tui.RefreshingEmailsMsg{Mailbox: msg.Mailbox} },
 299			refreshEmails(m.config, msg.Mailbox, msg.Counts),
 300		)
 301
 302	case tui.EmailsRefreshedMsg:
 303		if msg.Mailbox == tui.MailboxSent {
 304			m.sentByAcct = msg.EmailsByAccount
 305			m.sentEmails = flattenAndSort(msg.EmailsByAccount)
 306			if m.sentInbox != nil {
 307				m.sentInbox.SetEmails(m.sentEmails, m.config.Accounts)
 308				m.current, _ = m.current.Update(msg)
 309			}
 310			return m, nil
 311		}
 312
 313		m.emailsByAcct = msg.EmailsByAccount
 314		m.emails = flattenAndSort(msg.EmailsByAccount)
 315
 316		// Save to cache (inbox only)
 317		go saveEmailsToCache(m.emails)
 318
 319		// Update inbox if it exists
 320		if m.inbox != nil {
 321			m.inbox.SetEmails(m.emails, m.config.Accounts)
 322			// Forward the message to inbox to clear refreshing state
 323			m.current, _ = m.current.Update(msg)
 324		}
 325		return m, nil
 326
 327	case tui.AllEmailsFetchedMsg:
 328		if msg.Mailbox == tui.MailboxSent {
 329			m.sentByAcct = msg.EmailsByAccount
 330			m.sentEmails = flattenAndSort(msg.EmailsByAccount)
 331
 332			m.sentInbox = tui.NewSentInbox(m.sentEmails, m.config.Accounts)
 333			m.current = m.sentInbox
 334			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 335			return m, m.current.Init()
 336		}
 337
 338		if msg.Mailbox == tui.MailboxTrash {
 339			m.trashByAcct = msg.EmailsByAccount
 340			m.trashEmails = flattenAndSort(msg.EmailsByAccount)
 341
 342			// Create or update trash/archive view
 343			if m.trashArchive == nil {
 344				m.trashArchive = tui.NewTrashArchive(m.trashEmails, m.archiveEmails, m.config.Accounts)
 345			} else {
 346				m.trashArchive.SetTrashEmails(m.trashEmails, m.config.Accounts)
 347			}
 348			m.current = m.trashArchive
 349			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 350			return m, m.current.Init()
 351		}
 352
 353		if msg.Mailbox == tui.MailboxArchive {
 354			m.archiveByAcct = msg.EmailsByAccount
 355			m.archiveEmails = flattenAndSort(msg.EmailsByAccount)
 356
 357			// Create or update trash/archive view
 358			if m.trashArchive == nil {
 359				m.trashArchive = tui.NewTrashArchive(m.trashEmails, m.archiveEmails, m.config.Accounts)
 360			} else {
 361				m.trashArchive.SetArchiveEmails(m.archiveEmails, m.config.Accounts)
 362			}
 363			m.current = m.trashArchive
 364			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 365			return m, m.current.Init()
 366		}
 367
 368		m.emailsByAcct = msg.EmailsByAccount
 369		m.emails = flattenAndSort(msg.EmailsByAccount)
 370
 371		// Save to cache
 372		go saveEmailsToCache(m.emails)
 373
 374		m.inbox = tui.NewInbox(m.emails, m.config.Accounts)
 375		m.current = m.inbox
 376		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 377		return m, m.current.Init()
 378
 379	case tui.EmailsFetchedMsg:
 380		if msg.Mailbox == tui.MailboxSent {
 381			if m.sentByAcct == nil {
 382				m.sentByAcct = make(map[string][]fetcher.Email)
 383			}
 384			m.sentByAcct[msg.AccountID] = msg.Emails
 385			m.sentEmails = flattenAndSort(m.sentByAcct)
 386			if m.sentInbox == nil {
 387				m.sentInbox = tui.NewSentInbox(m.sentEmails, m.config.Accounts)
 388			} else {
 389				m.sentInbox.SetEmails(m.sentEmails, m.config.Accounts)
 390			}
 391			m.current = m.sentInbox
 392			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 393			return m, m.current.Init()
 394		}
 395
 396		// Inbox path
 397		if m.emailsByAcct == nil {
 398			m.emailsByAcct = make(map[string][]fetcher.Email)
 399		}
 400		m.emailsByAcct[msg.AccountID] = msg.Emails
 401		m.emails = flattenAndSort(m.emailsByAcct)
 402		if m.inbox == nil {
 403			m.inbox = tui.NewInbox(m.emails, m.config.Accounts)
 404		} else {
 405			m.inbox.SetEmails(m.emails, m.config.Accounts)
 406		}
 407		m.current = m.inbox
 408		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 409		return m, m.current.Init()
 410
 411	case tui.FetchMoreEmailsMsg:
 412		if msg.AccountID == "" {
 413			return m, nil // Don't fetch more for "ALL" view
 414		}
 415		account := m.config.GetAccountByID(msg.AccountID)
 416		if account == nil {
 417			return m, nil
 418		}
 419		limit := uint32(paginationLimit)
 420		if msg.Limit > 0 {
 421			limit = msg.Limit
 422		}
 423		return m, tea.Batch(
 424			func() tea.Msg { return tui.FetchingMoreEmailsMsg{} },
 425			fetchEmailsForMailbox(account, limit, msg.Offset, msg.Mailbox),
 426		)
 427
 428	case tui.EmailsAppendedMsg:
 429		if msg.Mailbox == tui.MailboxSent {
 430			if m.sentByAcct == nil {
 431				m.sentByAcct = make(map[string][]fetcher.Email)
 432			}
 433			unique := filterUnique(m.sentByAcct[msg.AccountID], msg.Emails)
 434			m.sentByAcct[msg.AccountID] = append(m.sentByAcct[msg.AccountID], unique...)
 435			m.sentEmails = append(m.sentEmails, unique...)
 436			return m, nil
 437		}
 438		if msg.Mailbox == tui.MailboxTrash {
 439			if m.trashByAcct == nil {
 440				m.trashByAcct = make(map[string][]fetcher.Email)
 441			}
 442			unique := filterUnique(m.trashByAcct[msg.AccountID], msg.Emails)
 443			m.trashByAcct[msg.AccountID] = append(m.trashByAcct[msg.AccountID], unique...)
 444			m.trashEmails = append(m.trashEmails, unique...)
 445			return m, nil
 446		}
 447		if msg.Mailbox == tui.MailboxArchive {
 448			if m.archiveByAcct == nil {
 449				m.archiveByAcct = make(map[string][]fetcher.Email)
 450			}
 451			unique := filterUnique(m.archiveByAcct[msg.AccountID], msg.Emails)
 452			m.archiveByAcct[msg.AccountID] = append(m.archiveByAcct[msg.AccountID], unique...)
 453			m.archiveEmails = append(m.archiveEmails, unique...)
 454			return m, nil
 455		}
 456		// Inbox
 457		if m.emailsByAcct == nil {
 458			m.emailsByAcct = make(map[string][]fetcher.Email)
 459		}
 460		unique := filterUnique(m.emailsByAcct[msg.AccountID], msg.Emails)
 461		m.emailsByAcct[msg.AccountID] = append(m.emailsByAcct[msg.AccountID], unique...)
 462		m.emails = append(m.emails, unique...)
 463
 464		// Save to cache
 465		go saveEmailsToCache(m.emails)
 466
 467		return m, nil
 468
 469	case tui.GoToSendMsg:
 470		if m.config != nil && len(m.config.Accounts) > 0 {
 471			firstAccount := m.config.GetFirstAccount()
 472			composer := tui.NewComposerWithAccounts(m.config.Accounts, firstAccount.ID, msg.To, msg.Subject, msg.Body)
 473			m.current = composer
 474		} else {
 475			m.current = tui.NewComposer("", msg.To, msg.Subject, msg.Body)
 476		}
 477		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 478		return m, m.current.Init()
 479
 480	case tui.GoToDraftsMsg:
 481		drafts := config.GetAllDrafts()
 482		m.current = tui.NewDrafts(drafts)
 483		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 484		return m, m.current.Init()
 485
 486	case tui.OpenDraftMsg:
 487		var accounts []config.Account
 488		if m.config != nil {
 489			accounts = m.config.Accounts
 490		}
 491		composer := tui.NewComposerFromDraft(msg.Draft, accounts)
 492		m.current = composer
 493		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 494		return m, m.current.Init()
 495
 496	case tui.DeleteSavedDraftMsg:
 497		go func() {
 498			if err := config.DeleteDraft(msg.DraftID); err != nil {
 499				log.Printf("Error deleting draft: %v", err)
 500			}
 501		}()
 502		// Send message back to drafts view
 503		m.current, cmd = m.current.Update(tui.DraftDeletedMsg{DraftID: msg.DraftID})
 504		return m, cmd
 505
 506	case tui.GoToSettingsMsg:
 507		m.current = tui.NewSettings(m.config)
 508		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 509		return m, m.current.Init()
 510
 511	case tui.GoToAddAccountMsg:
 512		m.current = tui.NewLogin()
 513		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 514		return m, m.current.Init()
 515
 516	case tui.GoToSignatureEditorMsg:
 517		m.current = tui.NewSignatureEditor()
 518		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 519		return m, m.current.Init()
 520
 521	case tui.GoToChoiceMenuMsg:
 522		m.current = tui.NewChoice()
 523		return m, m.current.Init()
 524
 525	case tui.DeleteAccountMsg:
 526		if m.config != nil {
 527			m.config.RemoveAccount(msg.AccountID)
 528			if err := config.SaveConfig(m.config); err != nil {
 529				log.Printf("could not save config: %v", err)
 530			}
 531			// Remove emails for this account
 532			delete(m.emailsByAcct, msg.AccountID)
 533
 534			// Rebuild all emails
 535			var allEmails []fetcher.Email
 536			for _, emails := range m.emailsByAcct {
 537				allEmails = append(allEmails, emails...)
 538			}
 539			m.emails = allEmails
 540
 541			// Go back to settings
 542			m.current = tui.NewSettings(m.config)
 543			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 544		}
 545		return m, m.current.Init()
 546
 547	case tui.ViewEmailMsg:
 548		email := m.getEmailByUIDAndAccount(msg.UID, msg.AccountID, msg.Mailbox)
 549		if email == nil {
 550			return m, nil
 551		}
 552		m.current = tui.NewStatus("Fetching email content...")
 553		return m, tea.Batch(m.current.Init(), fetchEmailBodyCmd(m.config, *email, msg.UID, msg.AccountID, msg.Mailbox))
 554
 555	case tui.EmailBodyFetchedMsg:
 556		if msg.Err != nil {
 557			log.Printf("could not fetch email body: %v", msg.Err)
 558			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 559				m.current = m.sentInbox
 560			} else {
 561				m.current = m.inbox
 562			}
 563			return m, nil
 564		}
 565
 566		// Update the email in our stores
 567		m.updateEmailBodyByUID(msg.UID, msg.AccountID, msg.Mailbox, msg.Body, msg.Attachments)
 568
 569		email := m.getEmailByUIDAndAccount(msg.UID, msg.AccountID, msg.Mailbox)
 570		if email == nil {
 571			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 572				m.current = m.sentInbox
 573			} else {
 574				m.current = m.inbox
 575			}
 576			return m, nil
 577		}
 578
 579		// Find the index for the email view (used for display purposes)
 580		emailIndex := m.getEmailIndex(msg.UID, msg.AccountID, msg.Mailbox)
 581		emailView := tui.NewEmailView(*email, emailIndex, m.width, m.height, msg.Mailbox, m.config.DisableImages)
 582		m.current = emailView
 583		return m, m.current.Init()
 584
 585	case tui.ReplyToEmailMsg:
 586		to := msg.Email.From
 587		subject := msg.Email.Subject
 588		normalizedSubject := strings.ToLower(strings.TrimSpace(subject))
 589		if !strings.HasPrefix(normalizedSubject, "re:") {
 590			subject = "Re: " + subject
 591		}
 592		quotedText := fmt.Sprintf("\n\nOn %s, %s wrote:\n> %s", msg.Email.Date.Format("Jan 2, 2006 at 3:04 PM"), msg.Email.From, strings.ReplaceAll(msg.Email.Body, "\n", "\n> "))
 593
 594		var composer *tui.Composer
 595		if m.config != nil && len(m.config.Accounts) > 0 {
 596			// Use the account that received the email
 597			accountID := msg.Email.AccountID
 598			if accountID == "" {
 599				accountID = m.config.GetFirstAccount().ID
 600			}
 601			composer = tui.NewComposerWithAccounts(m.config.Accounts, accountID, to, subject, "")
 602		} else {
 603			composer = tui.NewComposer("", to, subject, "")
 604		}
 605		composer.SetQuotedText(quotedText)
 606
 607		// Set reply headers
 608		inReplyTo := msg.Email.MessageID
 609		references := append(msg.Email.References, msg.Email.MessageID)
 610		composer.SetReplyContext(inReplyTo, references)
 611
 612		m.current = composer
 613		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 614		return m, m.current.Init()
 615
 616	case tui.ForwardEmailMsg:
 617		subject := msg.Email.Subject
 618		if !strings.HasPrefix(strings.ToLower(subject), "fwd:") {
 619			subject = "Fwd: " + subject
 620		}
 621
 622		forwardHeader := fmt.Sprintf("\n\n---------- Forwarded message ----------\nFrom: %s\nDate: %s\nSubject: %s\nTo: %s\n\n",
 623			msg.Email.From,
 624			msg.Email.Date.Format("Mon, Jan 2, 2006 at 3:04 PM"),
 625			msg.Email.Subject,
 626			msg.Email.To,
 627		)
 628
 629		body := forwardHeader + msg.Email.Body
 630
 631		var composer *tui.Composer
 632		if m.config != nil && len(m.config.Accounts) > 0 {
 633			// Use the account that received the email
 634			accountID := msg.Email.AccountID
 635			if accountID == "" {
 636				accountID = m.config.GetFirstAccount().ID
 637			}
 638			composer = tui.NewComposerWithAccounts(m.config.Accounts, accountID, "", subject, body)
 639		} else {
 640			composer = tui.NewComposer("", "", subject, body)
 641		}
 642
 643		m.current = composer
 644		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 645		return m, m.current.Init()
 646
 647	case tui.GoToFilePickerMsg:
 648		m.previousModel = m.current
 649		wd, _ := os.Getwd()
 650		m.current = tui.NewFilePicker(wd)
 651		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 652		return m, m.current.Init()
 653
 654	case tui.FileSelectedMsg, tui.CancelFilePickerMsg:
 655		if m.previousModel != nil {
 656			m.current = m.previousModel
 657			m.previousModel = nil
 658		}
 659		m.current, cmd = m.current.Update(msg)
 660		cmds = append(cmds, cmd)
 661
 662	case tui.SendEmailMsg:
 663		// Get draft ID before clearing composer (if it's a composer)
 664		var draftID string
 665		if composer, ok := m.current.(*tui.Composer); ok {
 666			draftID = composer.GetDraftID()
 667		}
 668		m.current = tui.NewStatus("Sending email...")
 669
 670		// Get the account to send from
 671		var account *config.Account
 672		if msg.AccountID != "" && m.config != nil {
 673			account = m.config.GetAccountByID(msg.AccountID)
 674		}
 675		if account == nil && m.config != nil {
 676			account = m.config.GetFirstAccount()
 677		}
 678
 679		// Save contact and delete draft in background
 680		go func() {
 681			// Save the recipient as a contact
 682			if msg.To != "" {
 683				// Parse "Name <email>" format
 684				name, email := parseEmailAddress(msg.To)
 685				if err := config.AddContact(name, email); err != nil {
 686					log.Printf("Error saving contact: %v", err)
 687				}
 688			}
 689			// Delete the draft since email is being sent
 690			if draftID != "" {
 691				if err := config.DeleteDraft(draftID); err != nil {
 692					log.Printf("Error deleting draft after send: %v", err)
 693				}
 694			}
 695		}()
 696
 697		return m, tea.Batch(m.current.Init(), sendEmail(account, msg))
 698
 699	case tui.EmailResultMsg:
 700		if msg.Err != nil {
 701			log.Printf("Failed to send email: %v", msg.Err)
 702			m.previousModel = tui.NewChoice()
 703			m.current = tui.NewStatus(fmt.Sprintf("Error: %v", msg.Err))
 704			return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
 705				return tui.RestoreViewMsg{}
 706			})
 707		}
 708		m.current = tui.NewChoice()
 709		return m, m.current.Init()
 710
 711	case tui.DeleteEmailMsg:
 712		m.previousModel = m.current
 713		m.current = tui.NewStatus("Deleting email...")
 714
 715		account := m.config.GetAccountByID(msg.AccountID)
 716		if account == nil {
 717			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 718				m.current = m.sentInbox
 719			} else {
 720				m.current = m.inbox
 721			}
 722			return m, nil
 723		}
 724
 725		return m, tea.Batch(m.current.Init(), deleteEmailCmd(account, msg.UID, msg.AccountID, msg.Mailbox))
 726
 727	case tui.ArchiveEmailMsg:
 728		m.previousModel = m.current
 729		m.current = tui.NewStatus("Archiving email...")
 730
 731		account := m.config.GetAccountByID(msg.AccountID)
 732		if account == nil {
 733			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 734				m.current = m.sentInbox
 735			} else {
 736				m.current = m.inbox
 737			}
 738			return m, nil
 739		}
 740
 741		return m, tea.Batch(m.current.Init(), archiveEmailCmd(account, msg.UID, msg.AccountID, msg.Mailbox))
 742
 743	case tui.EmailActionDoneMsg:
 744		if msg.Err != nil {
 745			log.Printf("Action failed: %v", msg.Err)
 746			m.previousModel = m.current
 747			switch msg.Mailbox {
 748			case tui.MailboxSent:
 749				if m.sentInbox != nil {
 750					m.previousModel = m.sentInbox
 751				}
 752			case tui.MailboxTrash, tui.MailboxArchive:
 753				if m.trashArchive != nil {
 754					m.previousModel = m.trashArchive
 755				}
 756			default:
 757				if m.inbox != nil {
 758					m.previousModel = m.inbox
 759				}
 760			}
 761			m.current = tui.NewStatus(fmt.Sprintf("Error: %v", msg.Err))
 762			return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
 763				return tui.RestoreViewMsg{}
 764			})
 765		}
 766
 767		// Remove email from stores
 768		m.removeEmailByMailbox(msg.UID, msg.AccountID, msg.Mailbox)
 769
 770		if msg.Mailbox == tui.MailboxSent {
 771			if m.sentInbox != nil {
 772				m.sentInbox.RemoveEmail(msg.UID, msg.AccountID)
 773				m.current = m.sentInbox
 774				m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 775				return m, m.current.Init()
 776			}
 777			m.current = tui.NewChoice()
 778			return m, m.current.Init()
 779		}
 780
 781		if msg.Mailbox == tui.MailboxTrash || msg.Mailbox == tui.MailboxArchive {
 782			if m.trashArchive != nil {
 783				m.trashArchive.RemoveEmail(msg.UID, msg.AccountID, msg.Mailbox)
 784				m.current = m.trashArchive
 785				m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 786				return m, m.current.Init()
 787			}
 788			m.current = tui.NewChoice()
 789			return m, m.current.Init()
 790		}
 791
 792		if m.inbox != nil {
 793			m.inbox.RemoveEmail(msg.UID, msg.AccountID)
 794			m.current = m.inbox
 795			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 796			return m, m.current.Init()
 797		}
 798		m.current = tui.NewChoice()
 799		return m, m.current.Init()
 800
 801	case tui.DownloadAttachmentMsg:
 802		m.previousModel = m.current
 803		m.current = tui.NewStatus(fmt.Sprintf("Downloading %s...", msg.Filename))
 804
 805		account := m.config.GetAccountByID(msg.AccountID)
 806		if account == nil {
 807			m.current = m.previousModel
 808			return m, nil
 809		}
 810
 811		email := m.getEmailByIndex(msg.Index, msg.Mailbox)
 812		if email == nil {
 813			m.current = m.previousModel
 814			return m, nil
 815		}
 816
 817		// Find the correct attachment to get encoding
 818		var encoding string
 819		for _, att := range email.Attachments {
 820			if att.PartID == msg.PartID {
 821				encoding = att.Encoding
 822				break
 823			}
 824		}
 825		newMsg := tui.DownloadAttachmentMsg{
 826			Index:     msg.Index,
 827			Filename:  msg.Filename,
 828			PartID:    msg.PartID,
 829			Data:      msg.Data,
 830			AccountID: msg.AccountID,
 831			Encoding:  encoding,
 832			Mailbox:   msg.Mailbox,
 833		}
 834		return m, tea.Batch(m.current.Init(), downloadAttachmentCmd(account, email.UID, newMsg))
 835
 836	case tui.AttachmentDownloadedMsg:
 837		var statusMsg string
 838		if msg.Err != nil {
 839			statusMsg = fmt.Sprintf("Error downloading: %v", msg.Err)
 840		} else {
 841			statusMsg = fmt.Sprintf("Saved to %s", msg.Path)
 842		}
 843		m.current = tui.NewStatus(statusMsg)
 844		return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
 845			return tui.RestoreViewMsg{}
 846		})
 847
 848	case tui.RestoreViewMsg:
 849		if m.previousModel != nil {
 850			m.current = m.previousModel
 851			m.previousModel = nil
 852		}
 853		return m, nil
 854	}
 855
 856	return m, tea.Batch(cmds...)
 857}
 858
 859func (m *mainModel) View() string {
 860	return m.current.View()
 861}
 862
 863func (m *mainModel) getEmailByIndex(index int, mailbox tui.MailboxKind) *fetcher.Email {
 864	switch mailbox {
 865	case tui.MailboxSent:
 866		if index >= 0 && index < len(m.sentEmails) {
 867			return &m.sentEmails[index]
 868		}
 869	case tui.MailboxTrash:
 870		if index >= 0 && index < len(m.trashEmails) {
 871			return &m.trashEmails[index]
 872		}
 873	case tui.MailboxArchive:
 874		if index >= 0 && index < len(m.archiveEmails) {
 875			return &m.archiveEmails[index]
 876		}
 877	default:
 878		if index >= 0 && index < len(m.emails) {
 879			return &m.emails[index]
 880		}
 881	}
 882	return nil
 883}
 884
 885func (m *mainModel) getEmailByUIDAndAccount(uid uint32, accountID string, mailbox tui.MailboxKind) *fetcher.Email {
 886	switch mailbox {
 887	case tui.MailboxSent:
 888		for i := range m.sentEmails {
 889			if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
 890				return &m.sentEmails[i]
 891			}
 892		}
 893	case tui.MailboxTrash:
 894		for i := range m.trashEmails {
 895			if m.trashEmails[i].UID == uid && m.trashEmails[i].AccountID == accountID {
 896				return &m.trashEmails[i]
 897			}
 898		}
 899	case tui.MailboxArchive:
 900		for i := range m.archiveEmails {
 901			if m.archiveEmails[i].UID == uid && m.archiveEmails[i].AccountID == accountID {
 902				return &m.archiveEmails[i]
 903			}
 904		}
 905	default:
 906		for i := range m.emails {
 907			if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
 908				return &m.emails[i]
 909			}
 910		}
 911	}
 912	return nil
 913}
 914
 915func (m *mainModel) getEmailIndex(uid uint32, accountID string, mailbox tui.MailboxKind) int {
 916	switch mailbox {
 917	case tui.MailboxSent:
 918		for i := range m.sentEmails {
 919			if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
 920				return i
 921			}
 922		}
 923	case tui.MailboxTrash:
 924		for i := range m.trashEmails {
 925			if m.trashEmails[i].UID == uid && m.trashEmails[i].AccountID == accountID {
 926				return i
 927			}
 928		}
 929	case tui.MailboxArchive:
 930		for i := range m.archiveEmails {
 931			if m.archiveEmails[i].UID == uid && m.archiveEmails[i].AccountID == accountID {
 932				return i
 933			}
 934		}
 935	default:
 936		for i := range m.emails {
 937			if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
 938				return i
 939			}
 940		}
 941	}
 942	return -1
 943}
 944
 945func (m *mainModel) updateEmailBodyByUID(uid uint32, accountID string, mailbox tui.MailboxKind, body string, attachments []fetcher.Attachment) {
 946	switch mailbox {
 947	case tui.MailboxSent:
 948		for i := range m.sentEmails {
 949			if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
 950				m.sentEmails[i].Body = body
 951				m.sentEmails[i].Attachments = attachments
 952				break
 953			}
 954		}
 955		if emails, ok := m.sentByAcct[accountID]; ok {
 956			for i := range emails {
 957				if emails[i].UID == uid {
 958					emails[i].Body = body
 959					emails[i].Attachments = attachments
 960					break
 961				}
 962			}
 963		}
 964	case tui.MailboxTrash:
 965		for i := range m.trashEmails {
 966			if m.trashEmails[i].UID == uid && m.trashEmails[i].AccountID == accountID {
 967				m.trashEmails[i].Body = body
 968				m.trashEmails[i].Attachments = attachments
 969				break
 970			}
 971		}
 972		if emails, ok := m.trashByAcct[accountID]; ok {
 973			for i := range emails {
 974				if emails[i].UID == uid {
 975					emails[i].Body = body
 976					emails[i].Attachments = attachments
 977					break
 978				}
 979			}
 980		}
 981	case tui.MailboxArchive:
 982		for i := range m.archiveEmails {
 983			if m.archiveEmails[i].UID == uid && m.archiveEmails[i].AccountID == accountID {
 984				m.archiveEmails[i].Body = body
 985				m.archiveEmails[i].Attachments = attachments
 986				break
 987			}
 988		}
 989		if emails, ok := m.archiveByAcct[accountID]; ok {
 990			for i := range emails {
 991				if emails[i].UID == uid {
 992					emails[i].Body = body
 993					emails[i].Attachments = attachments
 994					break
 995				}
 996			}
 997		}
 998	default:
 999		for i := range m.emails {
1000			if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
1001				m.emails[i].Body = body
1002				m.emails[i].Attachments = attachments
1003				break
1004			}
1005		}
1006		if emails, ok := m.emailsByAcct[accountID]; ok {
1007			for i := range emails {
1008				if emails[i].UID == uid {
1009					emails[i].Body = body
1010					emails[i].Attachments = attachments
1011					break
1012				}
1013			}
1014		}
1015	}
1016}
1017
1018func (m *mainModel) removeEmailByMailbox(uid uint32, accountID string, mailbox tui.MailboxKind) {
1019	switch mailbox {
1020	case tui.MailboxSent:
1021		var filtered []fetcher.Email
1022		for _, e := range m.sentEmails {
1023			if !(e.UID == uid && e.AccountID == accountID) {
1024				filtered = append(filtered, e)
1025			}
1026		}
1027		m.sentEmails = filtered
1028		if emails, ok := m.sentByAcct[accountID]; ok {
1029			var filteredAcct []fetcher.Email
1030			for _, e := range emails {
1031				if e.UID != uid {
1032					filteredAcct = append(filteredAcct, e)
1033				}
1034			}
1035			m.sentByAcct[accountID] = filteredAcct
1036		}
1037	case tui.MailboxTrash:
1038		var filtered []fetcher.Email
1039		for _, e := range m.trashEmails {
1040			if !(e.UID == uid && e.AccountID == accountID) {
1041				filtered = append(filtered, e)
1042			}
1043		}
1044		m.trashEmails = filtered
1045		if emails, ok := m.trashByAcct[accountID]; ok {
1046			var filteredAcct []fetcher.Email
1047			for _, e := range emails {
1048				if e.UID != uid {
1049					filteredAcct = append(filteredAcct, e)
1050				}
1051			}
1052			m.trashByAcct[accountID] = filteredAcct
1053		}
1054	case tui.MailboxArchive:
1055		var filtered []fetcher.Email
1056		for _, e := range m.archiveEmails {
1057			if !(e.UID == uid && e.AccountID == accountID) {
1058				filtered = append(filtered, e)
1059			}
1060		}
1061		m.archiveEmails = filtered
1062		if emails, ok := m.archiveByAcct[accountID]; ok {
1063			var filteredAcct []fetcher.Email
1064			for _, e := range emails {
1065				if e.UID != uid {
1066					filteredAcct = append(filteredAcct, e)
1067				}
1068			}
1069			m.archiveByAcct[accountID] = filteredAcct
1070		}
1071	default:
1072		var filtered []fetcher.Email
1073		for _, e := range m.emails {
1074			if !(e.UID == uid && e.AccountID == accountID) {
1075				filtered = append(filtered, e)
1076			}
1077		}
1078		m.emails = filtered
1079		if emails, ok := m.emailsByAcct[accountID]; ok {
1080			var filteredAcct []fetcher.Email
1081			for _, e := range emails {
1082				if e.UID != uid {
1083					filteredAcct = append(filteredAcct, e)
1084				}
1085			}
1086			m.emailsByAcct[accountID] = filteredAcct
1087		}
1088	}
1089}
1090
1091func flattenAndSort(emailsByAccount map[string][]fetcher.Email) []fetcher.Email {
1092	var allEmails []fetcher.Email
1093	for _, emails := range emailsByAccount {
1094		allEmails = append(allEmails, emails...)
1095	}
1096	for i := 0; i < len(allEmails); i++ {
1097		for j := i + 1; j < len(allEmails); j++ {
1098			if allEmails[j].Date.After(allEmails[i].Date) {
1099				allEmails[i], allEmails[j] = allEmails[j], allEmails[i]
1100			}
1101		}
1102	}
1103	return allEmails
1104}
1105
1106func fetchAllAccountsEmails(cfg *config.Config, mailbox tui.MailboxKind) tea.Cmd {
1107	return func() tea.Msg {
1108		emailsByAccount := make(map[string][]fetcher.Email)
1109		var mu sync.Mutex
1110		var wg sync.WaitGroup
1111
1112		for _, account := range cfg.Accounts {
1113			wg.Add(1)
1114			go func(acc config.Account) {
1115				defer wg.Done()
1116				var emails []fetcher.Email
1117				var err error
1118				switch mailbox {
1119				case tui.MailboxSent:
1120					emails, err = fetcher.FetchSentEmails(&acc, initialEmailLimit, 0)
1121				case tui.MailboxTrash:
1122					emails, err = fetcher.FetchTrashEmails(&acc, initialEmailLimit, 0)
1123				case tui.MailboxArchive:
1124					emails, err = fetcher.FetchArchiveEmails(&acc, initialEmailLimit, 0)
1125				default:
1126					emails, err = fetcher.FetchEmails(&acc, initialEmailLimit, 0)
1127				}
1128				if err != nil {
1129					log.Printf("Error fetching from %s: %v", acc.Email, err)
1130					return
1131				}
1132				mu.Lock()
1133				emailsByAccount[acc.ID] = emails
1134				mu.Unlock()
1135			}(account)
1136		}
1137
1138		wg.Wait()
1139		return tui.AllEmailsFetchedMsg{EmailsByAccount: emailsByAccount, Mailbox: mailbox}
1140	}
1141}
1142
1143func fetchEmails(account *config.Account, limit, offset uint32, mailbox tui.MailboxKind) tea.Cmd {
1144	return func() tea.Msg {
1145		var emails []fetcher.Email
1146		var err error
1147		if mailbox == tui.MailboxSent {
1148			emails, err = fetcher.FetchSentEmails(account, limit, offset)
1149		} else {
1150			emails, err = fetcher.FetchEmails(account, limit, offset)
1151		}
1152		if err != nil {
1153			return tui.FetchErr(err)
1154		}
1155		if offset == 0 {
1156			return tui.EmailsFetchedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1157		}
1158		return tui.EmailsAppendedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1159	}
1160}
1161
1162func fetchEmailsForMailbox(account *config.Account, limit, offset uint32, mailbox tui.MailboxKind) tea.Cmd {
1163	return func() tea.Msg {
1164		var emails []fetcher.Email
1165		var err error
1166		switch mailbox {
1167		case tui.MailboxSent:
1168			emails, err = fetcher.FetchSentEmails(account, limit, offset)
1169		case tui.MailboxTrash:
1170			emails, err = fetcher.FetchTrashEmails(account, limit, offset)
1171		case tui.MailboxArchive:
1172			emails, err = fetcher.FetchArchiveEmails(account, limit, offset)
1173		default:
1174			emails, err = fetcher.FetchEmails(account, limit, offset)
1175		}
1176		if err != nil {
1177			return tui.FetchErr(err)
1178		}
1179		if offset == 0 {
1180			return tui.EmailsFetchedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1181		}
1182		return tui.EmailsAppendedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1183	}
1184}
1185
1186func loadCachedEmails() tea.Cmd {
1187	return func() tea.Msg {
1188		cache, err := config.LoadEmailCache()
1189		if err != nil {
1190			return tui.CachedEmailsLoadedMsg{Cache: nil}
1191		}
1192		return tui.CachedEmailsLoadedMsg{Cache: cache}
1193	}
1194}
1195
1196func refreshEmails(cfg *config.Config, mailbox tui.MailboxKind, counts map[string]int) tea.Cmd {
1197	return func() tea.Msg {
1198		emailsByAccount := make(map[string][]fetcher.Email)
1199		var mu sync.Mutex
1200		var wg sync.WaitGroup
1201
1202		for _, account := range cfg.Accounts {
1203			wg.Add(1)
1204			go func(acc config.Account) {
1205				defer wg.Done()
1206				var emails []fetcher.Email
1207				var err error
1208
1209				limit := uint32(initialEmailLimit)
1210				if counts != nil {
1211					if c, ok := counts[acc.ID]; ok && c > 0 {
1212						limit = uint32(c)
1213					}
1214				}
1215
1216				if mailbox == tui.MailboxSent {
1217					emails, err = fetcher.FetchSentEmails(&acc, limit, 0)
1218				} else {
1219					emails, err = fetcher.FetchEmails(&acc, limit, 0)
1220				}
1221				if err != nil {
1222					log.Printf("Error fetching from %s: %v", acc.Email, err)
1223					return
1224				}
1225				mu.Lock()
1226				emailsByAccount[acc.ID] = emails
1227				mu.Unlock()
1228			}(account)
1229		}
1230
1231		wg.Wait()
1232		return tui.EmailsRefreshedMsg{EmailsByAccount: emailsByAccount, Mailbox: mailbox}
1233	}
1234}
1235
1236func saveEmailsToCache(emails []fetcher.Email) {
1237	if len(emails) > maxCacheEmails {
1238		emails = emails[:maxCacheEmails]
1239	}
1240	var cachedEmails []config.CachedEmail
1241	for _, email := range emails {
1242		cachedEmails = append(cachedEmails, config.CachedEmail{
1243			UID:       email.UID,
1244			From:      email.From,
1245			To:        email.To,
1246			Subject:   email.Subject,
1247			Date:      email.Date,
1248			MessageID: email.MessageID,
1249			AccountID: email.AccountID,
1250		})
1251
1252		// Save sender as a contact
1253		if email.From != "" {
1254			name, emailAddr := parseEmailAddress(email.From)
1255			if err := config.AddContact(name, emailAddr); err != nil {
1256				log.Printf("Error saving contact from email: %v", err)
1257			}
1258		}
1259	}
1260	cache := &config.EmailCache{Emails: cachedEmails}
1261	if err := config.SaveEmailCache(cache); err != nil {
1262		log.Printf("Error saving email cache: %v", err)
1263	}
1264}
1265
1266// parseEmailAddress parses "Name <email>" or just "email" format
1267func parseEmailAddress(addr string) (name, email string) {
1268	addr = strings.TrimSpace(addr)
1269	if idx := strings.Index(addr, "<"); idx != -1 {
1270		name = strings.TrimSpace(addr[:idx])
1271		endIdx := strings.Index(addr, ">")
1272		if endIdx > idx {
1273			email = strings.TrimSpace(addr[idx+1 : endIdx])
1274		} else {
1275			email = strings.TrimSpace(addr[idx+1:])
1276		}
1277	} else {
1278		email = addr
1279	}
1280	return name, email
1281}
1282
1283func fetchEmailBodyCmd(cfg *config.Config, email fetcher.Email, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1284	return func() tea.Msg {
1285		account := cfg.GetAccountByID(accountID)
1286		if account == nil {
1287			return tui.EmailBodyFetchedMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: fmt.Errorf("account not found")}
1288		}
1289
1290		var (
1291			body        string
1292			attachments []fetcher.Attachment
1293			err         error
1294		)
1295		switch mailbox {
1296		case tui.MailboxSent:
1297			body, attachments, err = fetcher.FetchSentEmailBody(account, uid)
1298		case tui.MailboxTrash:
1299			body, attachments, err = fetcher.FetchTrashEmailBody(account, uid)
1300		case tui.MailboxArchive:
1301			body, attachments, err = fetcher.FetchArchiveEmailBody(account, uid)
1302		default:
1303			body, attachments, err = fetcher.FetchEmailBody(account, uid)
1304		}
1305		if err != nil {
1306			return tui.EmailBodyFetchedMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1307		}
1308
1309		return tui.EmailBodyFetchedMsg{
1310			UID:         uid,
1311			Body:        body,
1312			Attachments: attachments,
1313			AccountID:   accountID,
1314			Mailbox:     mailbox,
1315		}
1316	}
1317}
1318
1319func markdownToHTML(md []byte) []byte {
1320	var buf bytes.Buffer
1321	p := goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
1322	if err := p.Convert(md, &buf); err != nil {
1323		return md
1324	}
1325	return buf.Bytes()
1326}
1327
1328func splitEmails(s string) []string {
1329	if s == "" {
1330		return nil
1331	}
1332	parts := strings.Split(s, ",")
1333	var res []string
1334	for _, p := range parts {
1335		if trimmed := strings.TrimSpace(p); trimmed != "" {
1336			res = append(res, trimmed)
1337		}
1338	}
1339	return res
1340}
1341
1342func sendEmail(account *config.Account, msg tui.SendEmailMsg) tea.Cmd {
1343	return func() tea.Msg {
1344		if account == nil {
1345			return tui.EmailResultMsg{Err: fmt.Errorf("no account configured")}
1346		}
1347
1348		recipients := splitEmails(msg.To)
1349		cc := splitEmails(msg.Cc)
1350		bcc := splitEmails(msg.Bcc)
1351		body := msg.Body
1352		// Append signature if present
1353		if msg.Signature != "" {
1354			body = body + "\n\n" + msg.Signature
1355		}
1356		// Append quoted text if present (for replies)
1357		if msg.QuotedText != "" {
1358			body = body + msg.QuotedText
1359		}
1360		images := make(map[string][]byte)
1361		attachments := make(map[string][]byte)
1362
1363		re := regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
1364		matches := re.FindAllStringSubmatch(body, -1)
1365
1366		for _, match := range matches {
1367			imgPath := match[1]
1368			imgData, err := os.ReadFile(imgPath)
1369			if err != nil {
1370				log.Printf("Could not read image file %s: %v", imgPath, err)
1371				continue
1372			}
1373			cid := fmt.Sprintf("%s%s@%s", uuid.NewString(), filepath.Ext(imgPath), "matcha")
1374			images[cid] = []byte(base64.StdEncoding.EncodeToString(imgData))
1375			body = strings.Replace(body, imgPath, "cid:"+cid, 1)
1376		}
1377
1378		htmlBody := markdownToHTML([]byte(body))
1379
1380		if msg.AttachmentPath != "" {
1381			fileData, err := os.ReadFile(msg.AttachmentPath)
1382			if err != nil {
1383				log.Printf("Could not read attachment file %s: %v", msg.AttachmentPath, err)
1384			} else {
1385				_, filename := filepath.Split(msg.AttachmentPath)
1386				attachments[filename] = fileData
1387			}
1388		}
1389
1390		err := sender.SendEmail(account, recipients, cc, bcc, msg.Subject, body, string(htmlBody), images, attachments, msg.InReplyTo, msg.References)
1391		if err != nil {
1392			log.Printf("Failed to send email: %v", err)
1393			return tui.EmailResultMsg{Err: err}
1394		}
1395		return tui.EmailResultMsg{}
1396	}
1397}
1398
1399func deleteEmailCmd(account *config.Account, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1400	return func() tea.Msg {
1401		var err error
1402		switch mailbox {
1403		case tui.MailboxSent:
1404			err = fetcher.DeleteSentEmail(account, uid)
1405		case tui.MailboxTrash:
1406			err = fetcher.DeleteTrashEmail(account, uid)
1407		case tui.MailboxArchive:
1408			err = fetcher.DeleteArchiveEmail(account, uid)
1409		default:
1410			err = fetcher.DeleteEmail(account, uid)
1411		}
1412		return tui.EmailActionDoneMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1413	}
1414}
1415
1416func archiveEmailCmd(account *config.Account, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1417	return func() tea.Msg {
1418		var err error
1419		if mailbox == tui.MailboxSent {
1420			err = fetcher.ArchiveSentEmail(account, uid)
1421		} else {
1422			err = fetcher.ArchiveEmail(account, uid)
1423		}
1424		return tui.EmailActionDoneMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1425	}
1426}
1427
1428func downloadAttachmentCmd(account *config.Account, uid uint32, msg tui.DownloadAttachmentMsg) tea.Cmd {
1429	return func() tea.Msg {
1430		// Download and decode the attachment using encoding provided in msg.Encoding.
1431		var data []byte
1432		var err error
1433		switch msg.Mailbox {
1434		case tui.MailboxSent:
1435			data, err = fetcher.FetchSentAttachment(account, uid, msg.PartID, msg.Encoding)
1436		case tui.MailboxTrash:
1437			data, err = fetcher.FetchTrashAttachment(account, uid, msg.PartID, msg.Encoding)
1438		case tui.MailboxArchive:
1439			data, err = fetcher.FetchArchiveAttachment(account, uid, msg.PartID, msg.Encoding)
1440		default:
1441			data, err = fetcher.FetchAttachment(account, uid, msg.PartID, msg.Encoding)
1442		}
1443		if err != nil {
1444			return tui.AttachmentDownloadedMsg{Err: err}
1445		}
1446
1447		homeDir, err := os.UserHomeDir()
1448		if err != nil {
1449			return tui.AttachmentDownloadedMsg{Err: err}
1450		}
1451		downloadsPath := filepath.Join(homeDir, "Downloads")
1452		if _, err := os.Stat(downloadsPath); os.IsNotExist(err) {
1453			if mkErr := os.MkdirAll(downloadsPath, 0755); mkErr != nil {
1454				return tui.AttachmentDownloadedMsg{Err: mkErr}
1455			}
1456		}
1457
1458		// Save the attachment using an exclusive create so we never overwrite an existing file.
1459		// If the filename already exists, append \" (n)\" before the extension.
1460		origName := msg.Filename
1461		ext := filepath.Ext(origName)
1462		base := strings.TrimSuffix(origName, ext)
1463		candidate := origName
1464		i := 1
1465		var filePath string
1466
1467		for {
1468			filePath = filepath.Join(downloadsPath, candidate)
1469
1470			// Try to create file exclusively. If it already exists, os.OpenFile will return an error
1471			// that satisfies os.IsExist(err), so we can increment the candidate.
1472			f, err := os.OpenFile(filePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
1473			if err != nil {
1474				if os.IsExist(err) {
1475					// file exists, try next candidate
1476					candidate = fmt.Sprintf("%s (%d)%s", base, i, ext)
1477					i++
1478					continue
1479				}
1480				// Some other error while attempting to create file
1481				log.Printf("error creating file %s: %v", filePath, err)
1482				return tui.AttachmentDownloadedMsg{Err: err}
1483			}
1484
1485			// Successfully created the file descriptor; write and close.
1486			if _, writeErr := f.Write(data); writeErr != nil {
1487				_ = f.Close()
1488				log.Printf("error writing to file %s: %v", filePath, writeErr)
1489				return tui.AttachmentDownloadedMsg{Err: writeErr}
1490			}
1491			if closeErr := f.Close(); closeErr != nil {
1492				log.Printf("warning: error closing file %s: %v", filePath, closeErr)
1493			}
1494
1495			// file saved successfully
1496			break
1497		}
1498
1499		log.Printf("attachment saved to %s", filePath)
1500
1501		// Try to open the file using a platform-specific opener asynchronously and log the outcome.
1502		go func(p string) {
1503			var cmd *exec.Cmd
1504			switch runtime.GOOS {
1505			case "darwin":
1506				cmd = exec.Command("open", p)
1507			case "linux":
1508				cmd = exec.Command("xdg-open", p)
1509			case "windows":
1510				// 'start' is a cmd builtin; provide an empty title argument to avoid interpreting the path as the title.
1511				cmd = exec.Command("cmd", "/c", "start", "", p)
1512			default:
1513				// Unsupported OS: nothing to do.
1514				return
1515			}
1516			if err := cmd.Start(); err != nil {
1517				log.Printf("failed to open file %s: %v", p, err)
1518			}
1519		}(filePath)
1520
1521		return tui.AttachmentDownloadedMsg{Path: filePath, Err: nil}
1522	}
1523}
1524
1525/*
1526detectInstalledVersion returns a best-effort installed version string.
1527Priority:
1528 1. If the build-in `version` variable is set to something other than "dev", return it.
1529 2. If Homebrew is present and reports a version for `matcha`, return that.
1530 3. If snap is present and lists `matcha`, return that.
1531 4. Fallback to the build `version` (likely "dev").
1532*/
1533func detectInstalledVersion() string {
1534	v := strings.TrimSpace(version)
1535	if v != "dev" && v != "" {
1536		return v
1537	}
1538
1539	// Try Homebrew (macOS)
1540	if runtime.GOOS == "darwin" {
1541		if _, err := exec.LookPath("brew"); err == nil {
1542			// `brew list --versions matcha` prints: matcha 1.2.3
1543			if out, err := exec.Command("brew", "list", "--versions", "matcha").Output(); err == nil {
1544				parts := strings.Fields(string(out))
1545				if len(parts) >= 2 {
1546					return parts[1]
1547				}
1548			}
1549		}
1550	}
1551
1552	// Try snap (Linux)
1553	if runtime.GOOS == "linux" {
1554		if _, err := exec.LookPath("snap"); err == nil {
1555			if out, err := exec.Command("snap", "list", "matcha").Output(); err == nil {
1556				lines := strings.Split(strings.TrimSpace(string(out)), "\n")
1557				if len(lines) >= 2 {
1558					fields := strings.Fields(lines[1])
1559					if len(fields) >= 2 {
1560						return fields[1]
1561					}
1562				}
1563			}
1564		}
1565
1566		if _, err := exec.LookPath("flatpak"); err == nil {
1567			if out, err := exec.Command("flatpak", "info", "com.floatpane.matcha").Output(); err == nil {
1568				lines := strings.Split(strings.TrimSpace(string(out)), "\n")
1569				for _, line := range lines {
1570					line = strings.TrimSpace(line)
1571					if strings.HasPrefix(line, "Version:") {
1572						fields := strings.Fields(line)
1573						if len(fields) >= 2 {
1574							return fields[1]
1575						}
1576					}
1577				}
1578			}
1579		}
1580	}
1581
1582	return v
1583}
1584
1585/*
1586checkForUpdatesCmd queries GitHub for the latest release tag and returns a
1587tea.Msg (UpdateAvailableMsg) if the latest version differs from the current
1588installed version. This runs in the background when the TUI initializes.
1589*/
1590func checkForUpdatesCmd() tea.Cmd {
1591	return func() tea.Msg {
1592		// Non-fatal: if anything goes wrong we just don't show the update message.
1593		const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
1594		resp, err := http.Get(api)
1595		if err != nil {
1596			return nil
1597		}
1598		defer resp.Body.Close()
1599
1600		var rel githubRelease
1601		if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
1602			return nil
1603		}
1604
1605		latest := strings.TrimPrefix(rel.TagName, "v")
1606		installed := strings.TrimPrefix(detectInstalledVersion(), "v")
1607		if latest != "" && installed != "" && latest != installed {
1608			return UpdateAvailableMsg{Latest: latest, Current: installed}
1609		}
1610		return nil
1611	}
1612}
1613
1614// runUpdateCLI implements the CLI entrypoint for `matcha update`.
1615// It detects the likely installation method and attempts the appropriate
1616// update path (Homebrew, Snap, or GitHub release binary extract).
1617func runUpdateCLI() error {
1618	const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
1619	resp, err := http.Get(api)
1620	if err != nil {
1621		return fmt.Errorf("could not query releases: %w", err)
1622	}
1623	defer resp.Body.Close()
1624
1625	var rel githubRelease
1626	if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
1627		return fmt.Errorf("could not parse release info: %w", err)
1628	}
1629
1630	latestTag := rel.TagName
1631	if strings.HasPrefix(latestTag, "v") {
1632		latestTag = latestTag[1:]
1633	}
1634
1635	fmt.Printf("Current version: %s\n", version)
1636	fmt.Printf("Latest version: %s\n", latestTag)
1637
1638	// Quick check: if already up-to-date, exit
1639	cur := version
1640	if strings.HasPrefix(cur, "v") {
1641		cur = cur[1:]
1642	}
1643	if latestTag == "" || cur == latestTag {
1644		fmt.Println("Already up to date.")
1645		return nil
1646	}
1647
1648	// Detect Homebrew
1649	if _, err := exec.LookPath("brew"); err == nil {
1650		fmt.Println("Detected Homebrew — updating taps and attempting to upgrade via brew.")
1651
1652		updateCmd := exec.Command("brew", "update")
1653		updateCmd.Stdout = os.Stdout
1654		updateCmd.Stderr = os.Stderr
1655		if err := updateCmd.Run(); err != nil {
1656			fmt.Printf("Homebrew update failed: %v\n", err)
1657			// continue to attempt upgrade even if update failed
1658		}
1659
1660		upgradeCmd := exec.Command("brew", "upgrade", "floatpane/matcha/matcha")
1661		upgradeCmd.Stdout = os.Stdout
1662		upgradeCmd.Stderr = os.Stderr
1663		if err := upgradeCmd.Run(); err == nil {
1664			fmt.Println("Successfully upgraded via Homebrew.")
1665			return nil
1666		}
1667		fmt.Printf("Homebrew upgrade failed: %v\n", err)
1668		// fallthrough to other methods
1669	}
1670
1671	// Detect snap
1672	if _, err := exec.LookPath("snap"); err == nil {
1673		// Check if matcha is installed as a snap
1674		cmdCheck := exec.Command("snap", "list", "matcha")
1675		if err := cmdCheck.Run(); err == nil {
1676			fmt.Println("Detected Snap package — attempting to refresh.")
1677			cmd := exec.Command("snap", "refresh", "matcha")
1678			cmd.Stdout = os.Stdout
1679			cmd.Stderr = os.Stderr
1680			if err := cmd.Run(); err == nil {
1681				fmt.Println("Successfully refreshed snap.")
1682				return nil
1683			}
1684			fmt.Printf("Snap refresh failed: %v\n", err)
1685			// fallthrough
1686		}
1687	}
1688	// Detect flatpak
1689	if _, err := exec.LookPath("flatpak"); err == nil {
1690		// Check if matcha is installed as a flatpak
1691		cmdCheck := exec.Command("flatpak", "info", "com.floatpane.matcha")
1692		if err := cmdCheck.Run(); err == nil {
1693			fmt.Println("Detected Flatpak package — attempting to update.")
1694			cmd := exec.Command("flatpak", "update", "-y", "com.floatpane.matcha")
1695			cmd.Stdout = os.Stdout
1696			cmd.Stderr = os.Stderr
1697			if err := cmd.Run(); err == nil {
1698				fmt.Println("Successfully updated flatpak.")
1699				return nil
1700			}
1701			fmt.Printf("Flatpak update failed: %v\n", err)
1702			// fallthrough
1703		}
1704	}
1705
1706	// Otherwise attempt to download the proper release asset and replace the binary.
1707	osName := runtime.GOOS
1708	arch := runtime.GOARCH
1709
1710	// Try to find a matching asset
1711	var assetURL, assetName string
1712	for _, a := range rel.Assets {
1713		n := strings.ToLower(a.Name)
1714		if strings.Contains(n, osName) && strings.Contains(n, arch) && (strings.HasSuffix(n, ".tar.gz") || strings.HasSuffix(n, ".tgz") || strings.HasSuffix(n, ".zip")) {
1715			assetURL = a.BrowserDownloadURL
1716			assetName = a.Name
1717			break
1718		}
1719	}
1720	if assetURL == "" {
1721		// Try any asset that contains 'matcha' and os/arch as a fallback
1722		for _, a := range rel.Assets {
1723			n := strings.ToLower(a.Name)
1724			if strings.Contains(n, "matcha") && (strings.Contains(n, osName) || strings.Contains(n, arch)) {
1725				assetURL = a.BrowserDownloadURL
1726				assetName = a.Name
1727				break
1728			}
1729		}
1730	}
1731
1732	if assetURL == "" {
1733		return fmt.Errorf("no suitable release artifact found for %s/%s", osName, arch)
1734	}
1735
1736	fmt.Printf("Found release asset: %s\n", assetName)
1737	fmt.Println("Downloading...")
1738
1739	// Download asset
1740	respAsset, err := http.Get(assetURL)
1741	if err != nil {
1742		return fmt.Errorf("download failed: %w", err)
1743	}
1744	defer respAsset.Body.Close()
1745
1746	// Create a temp file for the download
1747	tmpDir, err := os.MkdirTemp("", "matcha-update-*")
1748	if err != nil {
1749		return fmt.Errorf("could not create temp dir: %w", err)
1750	}
1751	defer os.RemoveAll(tmpDir)
1752
1753	assetPath := filepath.Join(tmpDir, assetName)
1754	outFile, err := os.Create(assetPath)
1755	if err != nil {
1756		return fmt.Errorf("could not create temp file: %w", err)
1757	}
1758	_, err = io.Copy(outFile, respAsset.Body)
1759	outFile.Close()
1760	if err != nil {
1761		return fmt.Errorf("could not write asset to disk: %w", err)
1762	}
1763
1764	// If it's a tar.gz, extract and find the `matcha` binary
1765	var binPath string
1766	if strings.HasSuffix(assetName, ".tar.gz") || strings.HasSuffix(assetName, ".tgz") {
1767		f, err := os.Open(assetPath)
1768		if err != nil {
1769			return fmt.Errorf("could not open archive: %w", err)
1770		}
1771		defer f.Close()
1772		gzr, err := gzip.NewReader(f)
1773		if err != nil {
1774			return fmt.Errorf("could not create gzip reader: %w", err)
1775		}
1776		tr := tar.NewReader(gzr)
1777		for {
1778			hdr, err := tr.Next()
1779			if err == io.EOF {
1780				break
1781			}
1782			if err != nil {
1783				return fmt.Errorf("error reading tar: %w", err)
1784			}
1785			name := filepath.Base(hdr.Name)
1786			if name == "matcha" || strings.Contains(strings.ToLower(name), "matcha") && (hdr.Typeflag == tar.TypeReg) {
1787				// write out the file
1788				binPath = filepath.Join(tmpDir, "matcha")
1789				out, err := os.Create(binPath)
1790				if err != nil {
1791					return fmt.Errorf("could not create binary file: %w", err)
1792				}
1793				if _, err := io.Copy(out, tr); err != nil {
1794					out.Close()
1795					return fmt.Errorf("could not extract binary: %w", err)
1796				}
1797				out.Close()
1798				if err := os.Chmod(binPath, 0755); err != nil {
1799					return fmt.Errorf("could not make binary executable: %w", err)
1800				}
1801				break
1802			}
1803		}
1804	} else {
1805		// For non-archive assets, assume the asset is the binary itself.
1806		binPath = assetPath
1807		if err := os.Chmod(binPath, 0755); err != nil {
1808			// ignore chmod errors but warn
1809			fmt.Printf("warning: could not chmod downloaded binary: %v\n", err)
1810		}
1811	}
1812
1813	if binPath == "" {
1814		return fmt.Errorf("could not locate matcha binary inside the release artifact")
1815	}
1816
1817	// Replace the running executable with the new binary
1818	execPath, err := os.Executable()
1819	if err != nil {
1820		return fmt.Errorf("could not determine executable path: %w", err)
1821	}
1822
1823	// Write the new binary to a temp file in same dir, then rename for atomic replacement.
1824	execDir := filepath.Dir(execPath)
1825	tmpNew := filepath.Join(execDir, fmt.Sprintf("matcha.new.%d", time.Now().Unix()))
1826	in, err := os.Open(binPath)
1827	if err != nil {
1828		return fmt.Errorf("could not open new binary: %w", err)
1829	}
1830	out, err := os.OpenFile(tmpNew, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
1831	if err != nil {
1832		in.Close()
1833		return fmt.Errorf("could not create temp binary in target dir: %w", err)
1834	}
1835	if _, err := io.Copy(out, in); err != nil {
1836		in.Close()
1837		out.Close()
1838		return fmt.Errorf("could not write new binary to disk: %w", err)
1839	}
1840	in.Close()
1841	out.Close()
1842
1843	// Attempt to atomically replace
1844	if err := os.Rename(tmpNew, execPath); err != nil {
1845		return fmt.Errorf("could not replace executable: %w", err)
1846	}
1847
1848	fmt.Println("Successfully updated matcha to", latestTag)
1849	return nil
1850}
1851
1852func filterUnique(existing, incoming []fetcher.Email) []fetcher.Email {
1853	seen := make(map[uint32]struct{})
1854	for _, e := range existing {
1855		seen[e.UID] = struct{}{}
1856	}
1857	var unique []fetcher.Email
1858	for _, e := range incoming {
1859		if _, ok := seen[e.UID]; !ok {
1860			unique = append(unique, e)
1861		}
1862	}
1863	return unique
1864}
1865
1866func main() {
1867	// If invoked as CLI update command, run updater and exit.
1868	if len(os.Args) > 1 && os.Args[1] == "update" {
1869		if err := runUpdateCLI(); err != nil {
1870			fmt.Fprintf(os.Stderr, "update failed: %v\n", err)
1871			os.Exit(1)
1872		}
1873		os.Exit(0)
1874	}
1875
1876	cfg, err := config.LoadConfig()
1877	var initialModel *mainModel
1878	if err != nil {
1879		initialModel = newInitialModel(nil)
1880	} else {
1881		initialModel = newInitialModel(cfg)
1882	}
1883
1884	p := tea.NewProgram(initialModel, tea.WithAltScreen())
1885
1886	if _, err := p.Run(); err != nil {
1887		fmt.Printf("Alas, there's been an error: %v", err)
1888		os.Exit(1)
1889	}
1890}