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