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		if msg.Err != nil {
 581			log.Printf("Failed to send email: %v", msg.Err)
 582			m.previousModel = tui.NewChoice()
 583			m.current = tui.NewStatus(fmt.Sprintf("Error: %v", msg.Err))
 584			return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
 585				return tui.RestoreViewMsg{}
 586			})
 587		}
 588		m.current = tui.NewChoice()
 589		return m, m.current.Init()
 590
 591	case tui.DeleteEmailMsg:
 592		m.previousModel = m.current
 593		m.current = tui.NewStatus("Deleting email...")
 594
 595		account := m.config.GetAccountByID(msg.AccountID)
 596		if account == nil {
 597			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 598				m.current = m.sentInbox
 599			} else {
 600				m.current = m.inbox
 601			}
 602			return m, nil
 603		}
 604
 605		return m, tea.Batch(m.current.Init(), deleteEmailCmd(account, msg.UID, msg.AccountID, msg.Mailbox))
 606
 607	case tui.ArchiveEmailMsg:
 608		m.previousModel = m.current
 609		m.current = tui.NewStatus("Archiving email...")
 610
 611		account := m.config.GetAccountByID(msg.AccountID)
 612		if account == nil {
 613			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 614				m.current = m.sentInbox
 615			} else {
 616				m.current = m.inbox
 617			}
 618			return m, nil
 619		}
 620
 621		return m, tea.Batch(m.current.Init(), archiveEmailCmd(account, msg.UID, msg.AccountID, msg.Mailbox))
 622
 623	case tui.EmailActionDoneMsg:
 624		if msg.Err != nil {
 625			log.Printf("Action failed: %v", msg.Err)
 626			m.previousModel = m.current
 627			if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
 628				m.previousModel = m.sentInbox
 629			} else if m.inbox != nil {
 630				m.previousModel = m.inbox
 631			}
 632			m.current = tui.NewStatus(fmt.Sprintf("Error: %v", msg.Err))
 633			return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
 634				return tui.RestoreViewMsg{}
 635			})
 636		}
 637
 638		// Remove email from stores
 639		m.removeEmailByMailbox(msg.UID, msg.AccountID, msg.Mailbox)
 640
 641		if msg.Mailbox == tui.MailboxSent {
 642			if m.sentInbox != nil {
 643				m.sentInbox.RemoveEmail(msg.UID, msg.AccountID)
 644				m.current = m.sentInbox
 645				m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 646				return m, m.current.Init()
 647			}
 648			m.current = tui.NewChoice()
 649			return m, m.current.Init()
 650		}
 651
 652		if m.inbox != nil {
 653			m.inbox.RemoveEmail(msg.UID, msg.AccountID)
 654			m.current = m.inbox
 655			m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
 656			return m, m.current.Init()
 657		}
 658		m.current = tui.NewChoice()
 659		return m, m.current.Init()
 660
 661	case tui.DownloadAttachmentMsg:
 662		m.previousModel = m.current
 663		m.current = tui.NewStatus(fmt.Sprintf("Downloading %s...", msg.Filename))
 664
 665		account := m.config.GetAccountByID(msg.AccountID)
 666		if account == nil {
 667			m.current = m.previousModel
 668			return m, nil
 669		}
 670
 671		email := m.getEmailByIndex(msg.Index, msg.Mailbox)
 672		if email == nil {
 673			m.current = m.previousModel
 674			return m, nil
 675		}
 676
 677		// Find the correct attachment to get encoding
 678		var encoding string
 679		for _, att := range email.Attachments {
 680			if att.PartID == msg.PartID {
 681				encoding = att.Encoding
 682				break
 683			}
 684		}
 685		newMsg := tui.DownloadAttachmentMsg{
 686			Index:     msg.Index,
 687			Filename:  msg.Filename,
 688			PartID:    msg.PartID,
 689			Data:      msg.Data,
 690			AccountID: msg.AccountID,
 691			Encoding:  encoding,
 692			Mailbox:   msg.Mailbox,
 693		}
 694		return m, tea.Batch(m.current.Init(), downloadAttachmentCmd(account, email.UID, newMsg))
 695
 696	case tui.AttachmentDownloadedMsg:
 697		var statusMsg string
 698		if msg.Err != nil {
 699			statusMsg = fmt.Sprintf("Error downloading: %v", msg.Err)
 700		} else {
 701			statusMsg = fmt.Sprintf("Saved to %s", msg.Path)
 702		}
 703		m.current = tui.NewStatus(statusMsg)
 704		return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
 705			return tui.RestoreViewMsg{}
 706		})
 707
 708	case tui.RestoreViewMsg:
 709		if m.previousModel != nil {
 710			m.current = m.previousModel
 711			m.previousModel = nil
 712		}
 713		return m, nil
 714	}
 715
 716	return m, tea.Batch(cmds...)
 717}
 718
 719func (m *mainModel) getEmailByIndex(index int, mailbox tui.MailboxKind) *fetcher.Email {
 720	switch mailbox {
 721	case tui.MailboxSent:
 722		if index >= 0 && index < len(m.sentEmails) {
 723			return &m.sentEmails[index]
 724		}
 725	default:
 726		if index >= 0 && index < len(m.emails) {
 727			return &m.emails[index]
 728		}
 729	}
 730	return nil
 731}
 732
 733func (m *mainModel) getEmailByUIDAndAccount(uid uint32, accountID string, mailbox tui.MailboxKind) *fetcher.Email {
 734	switch mailbox {
 735	case tui.MailboxSent:
 736		for i := range m.sentEmails {
 737			if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
 738				return &m.sentEmails[i]
 739			}
 740		}
 741	default:
 742		for i := range m.emails {
 743			if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
 744				return &m.emails[i]
 745			}
 746		}
 747	}
 748	return nil
 749}
 750
 751func (m *mainModel) getEmailIndex(uid uint32, accountID string, mailbox tui.MailboxKind) int {
 752	switch mailbox {
 753	case tui.MailboxSent:
 754		for i := range m.sentEmails {
 755			if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
 756				return i
 757			}
 758		}
 759	default:
 760		for i := range m.emails {
 761			if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
 762				return i
 763			}
 764		}
 765	}
 766	return -1
 767}
 768
 769func (m *mainModel) updateEmailBodyByUID(uid uint32, accountID string, mailbox tui.MailboxKind, body string, attachments []fetcher.Attachment) {
 770	switch mailbox {
 771	case tui.MailboxSent:
 772		for i := range m.sentEmails {
 773			if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
 774				m.sentEmails[i].Body = body
 775				m.sentEmails[i].Attachments = attachments
 776				break
 777			}
 778		}
 779		if emails, ok := m.sentByAcct[accountID]; ok {
 780			for i := range emails {
 781				if emails[i].UID == uid {
 782					emails[i].Body = body
 783					emails[i].Attachments = attachments
 784					break
 785				}
 786			}
 787		}
 788	default:
 789		for i := range m.emails {
 790			if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
 791				m.emails[i].Body = body
 792				m.emails[i].Attachments = attachments
 793				break
 794			}
 795		}
 796		if emails, ok := m.emailsByAcct[accountID]; ok {
 797			for i := range emails {
 798				if emails[i].UID == uid {
 799					emails[i].Body = body
 800					emails[i].Attachments = attachments
 801					break
 802				}
 803			}
 804		}
 805	}
 806}
 807
 808func (m *mainModel) removeEmailByMailbox(uid uint32, accountID string, mailbox tui.MailboxKind) {
 809	switch mailbox {
 810	case tui.MailboxSent:
 811		var filtered []fetcher.Email
 812		for _, e := range m.sentEmails {
 813			if !(e.UID == uid && e.AccountID == accountID) {
 814				filtered = append(filtered, e)
 815			}
 816		}
 817		m.sentEmails = filtered
 818		if emails, ok := m.sentByAcct[accountID]; ok {
 819			var filteredAcct []fetcher.Email
 820			for _, e := range emails {
 821				if e.UID != uid {
 822					filteredAcct = append(filteredAcct, e)
 823				}
 824			}
 825			m.sentByAcct[accountID] = filteredAcct
 826		}
 827	default:
 828		var filtered []fetcher.Email
 829		for _, e := range m.emails {
 830			if !(e.UID == uid && e.AccountID == accountID) {
 831				filtered = append(filtered, e)
 832			}
 833		}
 834		m.emails = filtered
 835		if emails, ok := m.emailsByAcct[accountID]; ok {
 836			var filteredAcct []fetcher.Email
 837			for _, e := range emails {
 838				if e.UID != uid {
 839					filteredAcct = append(filteredAcct, e)
 840				}
 841			}
 842			m.emailsByAcct[accountID] = filteredAcct
 843		}
 844	}
 845}
 846
 847func (m *mainModel) View() string {
 848	return m.current.View()
 849}
 850
 851func flattenAndSort(emailsByAccount map[string][]fetcher.Email) []fetcher.Email {
 852	var allEmails []fetcher.Email
 853	for _, emails := range emailsByAccount {
 854		allEmails = append(allEmails, emails...)
 855	}
 856	for i := 0; i < len(allEmails); i++ {
 857		for j := i + 1; j < len(allEmails); j++ {
 858			if allEmails[j].Date.After(allEmails[i].Date) {
 859				allEmails[i], allEmails[j] = allEmails[j], allEmails[i]
 860			}
 861		}
 862	}
 863	return allEmails
 864}
 865
 866func fetchAllAccountsEmails(cfg *config.Config, mailbox tui.MailboxKind) tea.Cmd {
 867	return func() tea.Msg {
 868		emailsByAccount := make(map[string][]fetcher.Email)
 869		var mu sync.Mutex
 870		var wg sync.WaitGroup
 871
 872		for _, account := range cfg.Accounts {
 873			wg.Add(1)
 874			go func(acc config.Account) {
 875				defer wg.Done()
 876				var emails []fetcher.Email
 877				var err error
 878				if mailbox == tui.MailboxSent {
 879					emails, err = fetcher.FetchSentEmails(&acc, initialEmailLimit, 0)
 880				} else {
 881					emails, err = fetcher.FetchEmails(&acc, initialEmailLimit, 0)
 882				}
 883				if err != nil {
 884					log.Printf("Error fetching from %s: %v", acc.Email, err)
 885					return
 886				}
 887				mu.Lock()
 888				emailsByAccount[acc.ID] = emails
 889				mu.Unlock()
 890			}(account)
 891		}
 892
 893		wg.Wait()
 894		return tui.AllEmailsFetchedMsg{EmailsByAccount: emailsByAccount, Mailbox: mailbox}
 895	}
 896}
 897
 898func fetchEmails(account *config.Account, limit, offset uint32, mailbox tui.MailboxKind) tea.Cmd {
 899	return func() tea.Msg {
 900		var emails []fetcher.Email
 901		var err error
 902		if mailbox == tui.MailboxSent {
 903			emails, err = fetcher.FetchSentEmails(account, limit, offset)
 904		} else {
 905			emails, err = fetcher.FetchEmails(account, limit, offset)
 906		}
 907		if err != nil {
 908			return tui.FetchErr(err)
 909		}
 910		if offset == 0 {
 911			return tui.EmailsFetchedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
 912		}
 913		return tui.EmailsAppendedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
 914	}
 915}
 916
 917func loadCachedEmails() tea.Cmd {
 918	return func() tea.Msg {
 919		cache, err := config.LoadEmailCache()
 920		if err != nil {
 921			return tui.CachedEmailsLoadedMsg{Cache: nil}
 922		}
 923		return tui.CachedEmailsLoadedMsg{Cache: cache}
 924	}
 925}
 926
 927func refreshEmails(cfg *config.Config, mailbox tui.MailboxKind) tea.Cmd {
 928	return func() tea.Msg {
 929		emailsByAccount := make(map[string][]fetcher.Email)
 930		var mu sync.Mutex
 931		var wg sync.WaitGroup
 932
 933		for _, account := range cfg.Accounts {
 934			wg.Add(1)
 935			go func(acc config.Account) {
 936				defer wg.Done()
 937				var emails []fetcher.Email
 938				var err error
 939				if mailbox == tui.MailboxSent {
 940					emails, err = fetcher.FetchSentEmails(&acc, initialEmailLimit, 0)
 941				} else {
 942					emails, err = fetcher.FetchEmails(&acc, initialEmailLimit, 0)
 943				}
 944				if err != nil {
 945					log.Printf("Error fetching from %s: %v", acc.Email, err)
 946					return
 947				}
 948				mu.Lock()
 949				emailsByAccount[acc.ID] = emails
 950				mu.Unlock()
 951			}(account)
 952		}
 953
 954		wg.Wait()
 955		return tui.EmailsRefreshedMsg{EmailsByAccount: emailsByAccount, Mailbox: mailbox}
 956	}
 957}
 958
 959func saveEmailsToCache(emails []fetcher.Email) {
 960	var cachedEmails []config.CachedEmail
 961	for _, email := range emails {
 962		cachedEmails = append(cachedEmails, config.CachedEmail{
 963			UID:       email.UID,
 964			From:      email.From,
 965			To:        email.To,
 966			Subject:   email.Subject,
 967			Date:      email.Date,
 968			MessageID: email.MessageID,
 969			AccountID: email.AccountID,
 970		})
 971
 972		// Save sender as a contact
 973		if email.From != "" {
 974			name, emailAddr := parseEmailAddress(email.From)
 975			if err := config.AddContact(name, emailAddr); err != nil {
 976				log.Printf("Error saving contact from email: %v", err)
 977			}
 978		}
 979	}
 980	cache := &config.EmailCache{Emails: cachedEmails}
 981	if err := config.SaveEmailCache(cache); err != nil {
 982		log.Printf("Error saving email cache: %v", err)
 983	}
 984}
 985
 986// parseEmailAddress parses "Name <email>" or just "email" format
 987func parseEmailAddress(addr string) (name, email string) {
 988	addr = strings.TrimSpace(addr)
 989	if idx := strings.Index(addr, "<"); idx != -1 {
 990		name = strings.TrimSpace(addr[:idx])
 991		endIdx := strings.Index(addr, ">")
 992		if endIdx > idx {
 993			email = strings.TrimSpace(addr[idx+1 : endIdx])
 994		} else {
 995			email = strings.TrimSpace(addr[idx+1:])
 996		}
 997	} else {
 998		email = addr
 999	}
1000	return name, email
1001}
1002
1003func fetchEmailBodyCmd(cfg *config.Config, email fetcher.Email, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1004	return func() tea.Msg {
1005		account := cfg.GetAccountByID(accountID)
1006		if account == nil {
1007			return tui.EmailBodyFetchedMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: fmt.Errorf("account not found")}
1008		}
1009
1010		var (
1011			body        string
1012			attachments []fetcher.Attachment
1013			err         error
1014		)
1015		if mailbox == tui.MailboxSent {
1016			body, attachments, err = fetcher.FetchSentEmailBody(account, uid)
1017		} else {
1018			body, attachments, err = fetcher.FetchEmailBody(account, uid)
1019		}
1020		if err != nil {
1021			return tui.EmailBodyFetchedMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1022		}
1023
1024		return tui.EmailBodyFetchedMsg{
1025			UID:         uid,
1026			Body:        body,
1027			Attachments: attachments,
1028			AccountID:   accountID,
1029			Mailbox:     mailbox,
1030		}
1031	}
1032}
1033
1034func markdownToHTML(md []byte) []byte {
1035	var buf bytes.Buffer
1036	p := goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
1037	if err := p.Convert(md, &buf); err != nil {
1038		return md
1039	}
1040	return buf.Bytes()
1041}
1042
1043func sendEmail(account *config.Account, msg tui.SendEmailMsg) tea.Cmd {
1044	return func() tea.Msg {
1045		if account == nil {
1046			return tui.EmailResultMsg{Err: fmt.Errorf("no account configured")}
1047		}
1048
1049		recipients := []string{msg.To}
1050		body := msg.Body
1051		// Append quoted text if present (for replies)
1052		if msg.QuotedText != "" {
1053			body = body + msg.QuotedText
1054		}
1055		images := make(map[string][]byte)
1056		attachments := make(map[string][]byte)
1057
1058		re := regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
1059		matches := re.FindAllStringSubmatch(body, -1)
1060
1061		for _, match := range matches {
1062			imgPath := match[1]
1063			imgData, err := os.ReadFile(imgPath)
1064			if err != nil {
1065				log.Printf("Could not read image file %s: %v", imgPath, err)
1066				continue
1067			}
1068			cid := fmt.Sprintf("%s%s@%s", uuid.NewString(), filepath.Ext(imgPath), "matcha")
1069			images[cid] = []byte(base64.StdEncoding.EncodeToString(imgData))
1070			body = strings.Replace(body, imgPath, "cid:"+cid, 1)
1071		}
1072
1073		htmlBody := markdownToHTML([]byte(body))
1074
1075		if msg.AttachmentPath != "" {
1076			fileData, err := os.ReadFile(msg.AttachmentPath)
1077			if err != nil {
1078				log.Printf("Could not read attachment file %s: %v", msg.AttachmentPath, err)
1079			} else {
1080				_, filename := filepath.Split(msg.AttachmentPath)
1081				attachments[filename] = fileData
1082			}
1083		}
1084
1085		err := sender.SendEmail(account, recipients, msg.Subject, msg.Body, string(htmlBody), images, attachments, msg.InReplyTo, msg.References)
1086		if err != nil {
1087			log.Printf("Failed to send email: %v", err)
1088			return tui.EmailResultMsg{Err: err}
1089		}
1090		return tui.EmailResultMsg{}
1091	}
1092}
1093
1094func deleteEmailCmd(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.DeleteSentEmail(account, uid)
1099		} else {
1100			err = fetcher.DeleteEmail(account, uid)
1101		}
1102		return tui.EmailActionDoneMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1103	}
1104}
1105
1106func archiveEmailCmd(account *config.Account, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1107	return func() tea.Msg {
1108		var err error
1109		if mailbox == tui.MailboxSent {
1110			err = fetcher.ArchiveSentEmail(account, uid)
1111		} else {
1112			err = fetcher.ArchiveEmail(account, uid)
1113		}
1114		return tui.EmailActionDoneMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1115	}
1116}
1117
1118func downloadAttachmentCmd(account *config.Account, uid uint32, msg tui.DownloadAttachmentMsg) tea.Cmd {
1119	return func() tea.Msg {
1120		// Download and decode the attachment using encoding provided in msg.Encoding.
1121		var data []byte
1122		var err error
1123		if msg.Mailbox == tui.MailboxSent {
1124			data, err = fetcher.FetchSentAttachment(account, uid, msg.PartID, msg.Encoding)
1125		} else {
1126			data, err = fetcher.FetchAttachment(account, uid, msg.PartID, msg.Encoding)
1127		}
1128		if err != nil {
1129			return tui.AttachmentDownloadedMsg{Err: err}
1130		}
1131
1132		homeDir, err := os.UserHomeDir()
1133		if err != nil {
1134			return tui.AttachmentDownloadedMsg{Err: err}
1135		}
1136		downloadsPath := filepath.Join(homeDir, "Downloads")
1137		if _, err := os.Stat(downloadsPath); os.IsNotExist(err) {
1138			if mkErr := os.MkdirAll(downloadsPath, 0755); mkErr != nil {
1139				return tui.AttachmentDownloadedMsg{Err: mkErr}
1140			}
1141		}
1142
1143		// Save the attachment using an exclusive create so we never overwrite an existing file.
1144		// If the filename already exists, append \" (n)\" before the extension.
1145		origName := msg.Filename
1146		ext := filepath.Ext(origName)
1147		base := strings.TrimSuffix(origName, ext)
1148		candidate := origName
1149		i := 1
1150		var filePath string
1151
1152		for {
1153			filePath = filepath.Join(downloadsPath, candidate)
1154
1155			// Try to create file exclusively. If it already exists, os.OpenFile will return an error
1156			// that satisfies os.IsExist(err), so we can increment the candidate.
1157			f, err := os.OpenFile(filePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
1158			if err != nil {
1159				if os.IsExist(err) {
1160					// file exists, try next candidate
1161					candidate = fmt.Sprintf("%s (%d)%s", base, i, ext)
1162					i++
1163					continue
1164				}
1165				// Some other error while attempting to create file
1166				log.Printf("error creating file %s: %v", filePath, err)
1167				return tui.AttachmentDownloadedMsg{Err: err}
1168			}
1169
1170			// Successfully created the file descriptor; write and close.
1171			if _, writeErr := f.Write(data); writeErr != nil {
1172				_ = f.Close()
1173				log.Printf("error writing to file %s: %v", filePath, writeErr)
1174				return tui.AttachmentDownloadedMsg{Err: writeErr}
1175			}
1176			if closeErr := f.Close(); closeErr != nil {
1177				log.Printf("warning: error closing file %s: %v", filePath, closeErr)
1178			}
1179
1180			// file saved successfully
1181			break
1182		}
1183
1184		log.Printf("attachment saved to %s", filePath)
1185
1186		// Try to open the file using a platform-specific opener asynchronously and log the outcome.
1187		go func(p string) {
1188			var cmd *exec.Cmd
1189			switch runtime.GOOS {
1190			case "darwin":
1191				cmd = exec.Command("open", p)
1192			case "linux":
1193				cmd = exec.Command("xdg-open", p)
1194			case "windows":
1195				// 'start' is a cmd builtin; provide an empty title argument to avoid interpreting the path as the title.
1196				cmd = exec.Command("cmd", "/c", "start", "", p)
1197			default:
1198				// Unsupported OS: nothing to do.
1199				return
1200			}
1201			if err := cmd.Start(); err != nil {
1202				log.Printf("failed to open file %s: %v", p, err)
1203			}
1204		}(filePath)
1205
1206		return tui.AttachmentDownloadedMsg{Path: filePath, Err: nil}
1207	}
1208}
1209
1210/*
1211detectInstalledVersion returns a best-effort installed version string.
1212Priority:
1213 1. If the build-in `version` variable is set to something other than "dev", return it.
1214 2. If Homebrew is present and reports a version for `matcha`, return that.
1215 3. If snap is present and lists `matcha`, return that.
1216 4. Fallback to the build `version` (likely "dev").
1217*/
1218func detectInstalledVersion() string {
1219	v := strings.TrimSpace(version)
1220	if v != "dev" && v != "" {
1221		return v
1222	}
1223
1224	// Try Homebrew (macOS)
1225	if runtime.GOOS == "darwin" {
1226		if _, err := exec.LookPath("brew"); err == nil {
1227			// `brew list --versions matcha` prints: matcha 1.2.3
1228			if out, err := exec.Command("brew", "list", "--versions", "matcha").Output(); err == nil {
1229				parts := strings.Fields(string(out))
1230				if len(parts) >= 2 {
1231					return parts[1]
1232				}
1233			}
1234		}
1235	}
1236
1237	// Try snap (Linux)
1238	if runtime.GOOS == "linux" {
1239		if _, err := exec.LookPath("snap"); err == nil {
1240			if out, err := exec.Command("snap", "list", "matcha").Output(); err == nil {
1241				lines := strings.Split(strings.TrimSpace(string(out)), "\n")
1242				if len(lines) >= 2 {
1243					fields := strings.Fields(lines[1])
1244					if len(fields) >= 2 {
1245						return fields[1]
1246					}
1247				}
1248			}
1249		}
1250	}
1251
1252	return v
1253}
1254
1255/*
1256checkForUpdatesCmd queries GitHub for the latest release tag and returns a
1257tea.Msg (UpdateAvailableMsg) if the latest version differs from the current
1258installed version. This runs in the background when the TUI initializes.
1259*/
1260func checkForUpdatesCmd() tea.Cmd {
1261	return func() tea.Msg {
1262		// Non-fatal: if anything goes wrong we just don't show the update message.
1263		const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
1264		resp, err := http.Get(api)
1265		if err != nil {
1266			return nil
1267		}
1268		defer resp.Body.Close()
1269
1270		var rel githubRelease
1271		if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
1272			return nil
1273		}
1274
1275		latest := strings.TrimPrefix(rel.TagName, "v")
1276		installed := strings.TrimPrefix(detectInstalledVersion(), "v")
1277		if latest != "" && installed != "" && latest != installed {
1278			return UpdateAvailableMsg{Latest: latest, Current: installed}
1279		}
1280		return nil
1281	}
1282}
1283
1284// runUpdateCLI implements the CLI entrypoint for `matcha update`.
1285// It detects the likely installation method and attempts the appropriate
1286// update path (Homebrew, Snap, or GitHub release binary extract).
1287func runUpdateCLI() error {
1288	const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
1289	resp, err := http.Get(api)
1290	if err != nil {
1291		return fmt.Errorf("could not query releases: %w", err)
1292	}
1293	defer resp.Body.Close()
1294
1295	var rel githubRelease
1296	if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
1297		return fmt.Errorf("could not parse release info: %w", err)
1298	}
1299
1300	latestTag := rel.TagName
1301	if strings.HasPrefix(latestTag, "v") {
1302		latestTag = latestTag[1:]
1303	}
1304
1305	fmt.Printf("Current version: %s\n", version)
1306	fmt.Printf("Latest version: %s\n", latestTag)
1307
1308	// Quick check: if already up-to-date, exit
1309	cur := version
1310	if strings.HasPrefix(cur, "v") {
1311		cur = cur[1:]
1312	}
1313	if latestTag == "" || cur == latestTag {
1314		fmt.Println("Already up to date.")
1315		return nil
1316	}
1317
1318	// Detect Homebrew
1319	if _, err := exec.LookPath("brew"); err == nil {
1320		fmt.Println("Detected Homebrew — updating taps and attempting to upgrade via brew.")
1321
1322		updateCmd := exec.Command("brew", "update")
1323		updateCmd.Stdout = os.Stdout
1324		updateCmd.Stderr = os.Stderr
1325		if err := updateCmd.Run(); err != nil {
1326			fmt.Printf("Homebrew update failed: %v\n", err)
1327			// continue to attempt upgrade even if update failed
1328		}
1329
1330		upgradeCmd := exec.Command("brew", "upgrade", "floatpane/matcha/matcha")
1331		upgradeCmd.Stdout = os.Stdout
1332		upgradeCmd.Stderr = os.Stderr
1333		if err := upgradeCmd.Run(); err == nil {
1334			fmt.Println("Successfully upgraded via Homebrew.")
1335			return nil
1336		}
1337		fmt.Printf("Homebrew upgrade failed: %v\n", err)
1338		// fallthrough to other methods
1339	}
1340
1341	// Detect snap
1342	if _, err := exec.LookPath("snap"); err == nil {
1343		// Check if matcha is installed as a snap
1344		cmdCheck := exec.Command("snap", "list", "matcha")
1345		if err := cmdCheck.Run(); err == nil {
1346			fmt.Println("Detected Snap package — attempting to refresh.")
1347			cmd := exec.Command("snap", "refresh", "matcha")
1348			cmd.Stdout = os.Stdout
1349			cmd.Stderr = os.Stderr
1350			if err := cmd.Run(); err == nil {
1351				fmt.Println("Successfully refreshed snap.")
1352				return nil
1353			}
1354			fmt.Printf("Snap refresh failed: %v\n", err)
1355			// fallthrough
1356		}
1357	}
1358
1359	// Otherwise attempt to download the proper release asset and replace the binary.
1360	osName := runtime.GOOS
1361	arch := runtime.GOARCH
1362
1363	// Try to find a matching asset
1364	var assetURL, assetName string
1365	for _, a := range rel.Assets {
1366		n := strings.ToLower(a.Name)
1367		if strings.Contains(n, osName) && strings.Contains(n, arch) && (strings.HasSuffix(n, ".tar.gz") || strings.HasSuffix(n, ".tgz") || strings.HasSuffix(n, ".zip")) {
1368			assetURL = a.BrowserDownloadURL
1369			assetName = a.Name
1370			break
1371		}
1372	}
1373	if assetURL == "" {
1374		// Try any asset that contains 'matcha' and os/arch as a fallback
1375		for _, a := range rel.Assets {
1376			n := strings.ToLower(a.Name)
1377			if strings.Contains(n, "matcha") && (strings.Contains(n, osName) || strings.Contains(n, arch)) {
1378				assetURL = a.BrowserDownloadURL
1379				assetName = a.Name
1380				break
1381			}
1382		}
1383	}
1384
1385	if assetURL == "" {
1386		return fmt.Errorf("no suitable release artifact found for %s/%s", osName, arch)
1387	}
1388
1389	fmt.Printf("Found release asset: %s\n", assetName)
1390	fmt.Println("Downloading...")
1391
1392	// Download asset
1393	respAsset, err := http.Get(assetURL)
1394	if err != nil {
1395		return fmt.Errorf("download failed: %w", err)
1396	}
1397	defer respAsset.Body.Close()
1398
1399	// Create a temp file for the download
1400	tmpDir, err := os.MkdirTemp("", "matcha-update-*")
1401	if err != nil {
1402		return fmt.Errorf("could not create temp dir: %w", err)
1403	}
1404	defer os.RemoveAll(tmpDir)
1405
1406	assetPath := filepath.Join(tmpDir, assetName)
1407	outFile, err := os.Create(assetPath)
1408	if err != nil {
1409		return fmt.Errorf("could not create temp file: %w", err)
1410	}
1411	_, err = io.Copy(outFile, respAsset.Body)
1412	outFile.Close()
1413	if err != nil {
1414		return fmt.Errorf("could not write asset to disk: %w", err)
1415	}
1416
1417	// If it's a tar.gz, extract and find the `matcha` binary
1418	var binPath string
1419	if strings.HasSuffix(assetName, ".tar.gz") || strings.HasSuffix(assetName, ".tgz") {
1420		f, err := os.Open(assetPath)
1421		if err != nil {
1422			return fmt.Errorf("could not open archive: %w", err)
1423		}
1424		defer f.Close()
1425		gzr, err := gzip.NewReader(f)
1426		if err != nil {
1427			return fmt.Errorf("could not create gzip reader: %w", err)
1428		}
1429		tr := tar.NewReader(gzr)
1430		for {
1431			hdr, err := tr.Next()
1432			if err == io.EOF {
1433				break
1434			}
1435			if err != nil {
1436				return fmt.Errorf("error reading tar: %w", err)
1437			}
1438			name := filepath.Base(hdr.Name)
1439			if name == "matcha" || strings.Contains(strings.ToLower(name), "matcha") && (hdr.Typeflag == tar.TypeReg) {
1440				// write out the file
1441				binPath = filepath.Join(tmpDir, "matcha")
1442				out, err := os.Create(binPath)
1443				if err != nil {
1444					return fmt.Errorf("could not create binary file: %w", err)
1445				}
1446				if _, err := io.Copy(out, tr); err != nil {
1447					out.Close()
1448					return fmt.Errorf("could not extract binary: %w", err)
1449				}
1450				out.Close()
1451				if err := os.Chmod(binPath, 0755); err != nil {
1452					return fmt.Errorf("could not make binary executable: %w", err)
1453				}
1454				break
1455			}
1456		}
1457	} else {
1458		// For non-archive assets, assume the asset is the binary itself.
1459		binPath = assetPath
1460		if err := os.Chmod(binPath, 0755); err != nil {
1461			// ignore chmod errors but warn
1462			fmt.Printf("warning: could not chmod downloaded binary: %v\n", err)
1463		}
1464	}
1465
1466	if binPath == "" {
1467		return fmt.Errorf("could not locate matcha binary inside the release artifact")
1468	}
1469
1470	// Replace the running executable with the new binary
1471	execPath, err := os.Executable()
1472	if err != nil {
1473		return fmt.Errorf("could not determine executable path: %w", err)
1474	}
1475
1476	// Write the new binary to a temp file in same dir, then rename for atomic replacement.
1477	execDir := filepath.Dir(execPath)
1478	tmpNew := filepath.Join(execDir, fmt.Sprintf("matcha.new.%d", time.Now().Unix()))
1479	in, err := os.Open(binPath)
1480	if err != nil {
1481		return fmt.Errorf("could not open new binary: %w", err)
1482	}
1483	out, err := os.OpenFile(tmpNew, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
1484	if err != nil {
1485		in.Close()
1486		return fmt.Errorf("could not create temp binary in target dir: %w", err)
1487	}
1488	if _, err := io.Copy(out, in); err != nil {
1489		in.Close()
1490		out.Close()
1491		return fmt.Errorf("could not write new binary to disk: %w", err)
1492	}
1493	in.Close()
1494	out.Close()
1495
1496	// Attempt to atomically replace
1497	if err := os.Rename(tmpNew, execPath); err != nil {
1498		return fmt.Errorf("could not replace executable: %w", err)
1499	}
1500
1501	fmt.Println("Successfully updated matcha to", latestTag)
1502	return nil
1503}
1504
1505func main() {
1506	// If invoked as CLI update command, run updater and exit.
1507	if len(os.Args) > 1 && os.Args[1] == "update" {
1508		if err := runUpdateCLI(); err != nil {
1509			fmt.Fprintf(os.Stderr, "update failed: %v\n", err)
1510			os.Exit(1)
1511		}
1512		os.Exit(0)
1513	}
1514
1515	cfg, err := config.LoadConfig()
1516	var initialModel *mainModel
1517	if err != nil {
1518		initialModel = newInitialModel(nil)
1519	} else {
1520		initialModel = newInitialModel(cfg)
1521	}
1522
1523	p := tea.NewProgram(initialModel, tea.WithAltScreen())
1524
1525	if _, err := p.Run(); err != nil {
1526		fmt.Printf("Alas, there's been an error: %v", err)
1527		os.Exit(1)
1528	}
1529}