# window.py — the main window
#
# SPDX-License-Identifier: GPL-3.0-or-later

import csv
import time
from gettext import gettext as _, ngettext

from gi.repository import Adw, Gio, GLib, Gtk, Pango

from . import formatting
from .chart import AllocationBar, Dot, PriceChart
from .dialogs import HoldingDialog, PositionDialog, set_direction_class
from .exchanges import BASE_CURRENCIES, EXCHANGES, get_exchange
from .model import parse_portfolio_csv, price_looks_wrong, summarize, value_positions
from .providers import PROVIDERS_BY_ID


def _clear(box):
    child = box.get_first_child()
    while child is not None:
        nxt = child.get_next_sibling()
        box.remove(child)
        child = nxt


class SummaryCard(Gtk.Box):
    def __init__(self):
        super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=6,
                         css_classes=["card", "summary-card"])
        self.caption = Gtk.Label(xalign=0, label=_("Portfolio Value"),
                                 css_classes=["caption-heading", "dim-label"])
        self.value = Gtk.Label(xalign=0, css_classes=["title-1", "numeric"], selectable=True,
                               ellipsize=Pango.EllipsizeMode.END)
        self.day = Gtk.Label(xalign=0, css_classes=["numeric", "change-text"])
        self.gain = Gtk.Label(xalign=0, css_classes=["numeric", "change-text"])
        lines = Gtk.Box(spacing=18, margin_bottom=6)
        lines.append(self._pair(_("Today"), self.day))
        lines.append(self._pair(_("Total Return"), self.gain))
        self.bar = AllocationBar()
        self.bar.set_margin_top(6)
        self.legend = Gtk.FlowBox(selection_mode=Gtk.SelectionMode.NONE,
                                  max_children_per_line=3, column_spacing=12,
                                  homogeneous=False)
        self.note = Gtk.Label(xalign=0, wrap=True, css_classes=["caption", "dim-label"],
                              visible=False)
        for w in (self.caption, self.value, lines, self.bar, self.legend, self.note):
            self.append(w)

    @staticmethod
    def _pair(title, label):
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        box.append(Gtk.Label(label=title, xalign=0, css_classes=["caption", "dim-label"]))
        box.append(label)
        return box

    def update(self, summary, loading):
        base = summary.base_currency
        if summary.priced == 0:
            self.value.set_label(_("Loading…") if loading else "—")
            self.day.set_label("—")
            self.gain.set_label("—")
        else:
            self.value.set_label(formatting.money(summary.value, base))
            self.day.set_label("{}  {}".format(formatting.signed_money(summary.day_change, base),
                                               formatting.percent(summary.day_percent)))
            self.gain.set_label("{}  {}".format(formatting.signed_money(summary.gain, base),
                                                formatting.percent(summary.gain_percent)))
        set_direction_class(self.day, summary.day_change if summary.priced else None)
        set_direction_class(self.gain, summary.gain if summary.priced else None)

        allocation = summary.allocation()
        self.bar.set_parts([(e.color, f) for e, f in allocation])
        self.bar.set_visible(bool(allocation))
        self.legend.remove_all()
        for e, f in allocation:
            item = Gtk.Box(spacing=6)
            item.append(Dot(e.color, 8))
            item.append(Gtk.Label(label=f"{e.short_name}  {formatting.number(f * 100, 1)} %",
                                  css_classes=["caption", "numeric"]))
            self.legend.append(item)

        if summary.missing and not loading:
            self.note.set_label(ngettext(
                "{n} holding has no current price and is not included",
                "{n} holdings have no current price and are not included",
                summary.missing).format(n=summary.missing))
            self.note.set_visible(True)
        else:
            self.note.set_visible(False)


class PositionRow(Adw.ActionRow):
    def __init__(self, position, base_currency, share_of_total, stale=False):
        super().__init__(activatable=True, use_markup=False)
        h, q = position.holding, position.quote
        cur = position.currency or ""
        self.holding_id = h.id
        self.set_title(h.name or h.display_symbol)
        self.set_title_lines(1)

        badge = Gtk.Label(label=h.display_symbol, valign=Gtk.Align.CENTER,
                          css_classes=["ticker-badge"], width_chars=6, max_width_chars=9,
                          ellipsize=Pango.EllipsizeMode.END)
        self.add_prefix(badge)

        if q:
            subtitle = ngettext("{n} share · {price}", "{n} shares · {price}",
                                2 if h.shares != 1 else 1).format(
                n=formatting.shares(h.shares), price=formatting.money(q.price, cur))
            if position.gain_percent is not None:
                subtitle += "  ·  " + _("{pct} total").format(
                    pct=formatting.percent(position.gain_percent))
        else:
            subtitle = ngettext("{n} share", "{n} shares", 2 if h.shares != 1 else 1).format(
                n=formatting.shares(h.shares)) + "  ·  " + _("no price")
        self.set_subtitle(subtitle)
        self.set_subtitle_lines(1)

        if q and price_looks_wrong(h.cost, q.price):
            warn = Gtk.Image(icon_name="dialog-warning-symbolic", valign=Gtk.Align.CENTER,
                             css_classes=["warning"])
            warn.set_tooltip_text(_("Your average price {cost} is far from the market price. "
                                    "Check that it is per share and in {currency}.").format(
                cost=formatting.money(h.cost, cur), currency=cur))
            self.add_suffix(warn)

        if stale and q:
            clock = Gtk.Image(icon_name="document-open-recent-symbolic",
                              valign=Gtk.Align.CENTER, css_classes=["dim-label"])
            clock.set_tooltip_text(_("Saved price from {time}; it could not be updated").format(
                time=formatting.clock(q.fetched_at)))
            self.add_suffix(clock)

        if q and len(q.points) > 1:
            spark = PriceChart(compact=True)
            spark.set_data(q.points, q.previous_close)
            spark.set_margin_end(6)
            self.add_suffix(spark)

        figures = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4,
                          valign=Gtk.Align.CENTER)
        value = position.value_base if position.value_base is not None else position.market_value
        value_cur = base_currency if position.value_base is not None else cur
        value_label = Gtk.Label(label=formatting.money(value, value_cur, 0), xalign=1,
                                css_classes=["numeric", "heading"])
        if stale:
            value_label.add_css_class("stale")
        figures.append(value_label)
        pill = Gtk.Label(label=formatting.percent(position.day_percent), xalign=1,
                         halign=Gtk.Align.END, css_classes=["numeric", "change-pill"])
        set_direction_class(pill, position.day_percent)
        figures.append(pill)
        self.add_suffix(figures)

        self.set_tooltip_text(_("{pct} of portfolio").format(
            pct=formatting.percent(share_of_total * 100, signed=False))
            if share_of_total else None)


class PortfolioWindow(Adw.ApplicationWindow):
    def __init__(self, application):
        super().__init__(application=application, title=_("Portfolio"))
        self.set_default_size(600, 820)
        self.set_size_request(360, 400)
        self.app = application
        self.portfolio = application.portfolio
        self.service = application.service
        self.last_exchange = EXCHANGES[0].id
        self.refreshing = False
        self.detail = None
        self._undo = None
        self._timer = 0
        self._retry_timer = 0
        self._user_refresh = False
        self.last_result = None

        # header bar
        header = Adw.HeaderBar()
        self.window_title = Adw.WindowTitle(title=_("Portfolio"))
        header.set_title_widget(self.window_title)
        header.pack_start(Gtk.Button(icon_name="list-add-symbolic",
                                     tooltip_text=_("Add Stock"), action_name="win.add"))
        header.pack_end(Gtk.MenuButton(icon_name="open-menu-symbolic", primary=True,
                                       tooltip_text=_("Main Menu"),
                                       menu_model=self._build_menu()))
        self.refresh_stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE)
        self.refresh_stack.add_named(Gtk.Button(icon_name="view-refresh-symbolic",
                                                tooltip_text=_("Refresh"),
                                                action_name="win.refresh"), "button")
        self.refresh_stack.add_named(Adw.Spinner(), "spinner")
        header.pack_end(self.refresh_stack)

        # empty state
        empty = Adw.StatusPage(
            icon_name="org.gnome.PortfolioManager-symbolic",
            title=_("No Stocks Yet"),
            description=_("Track shares listed on the New York Stock Exchange, "
                          "Nasdaq Stockholm and Oslo Børs"))
        add = Gtk.Button(label=_("_Add Stock"), use_underline=True, halign=Gtk.Align.CENTER,
                         action_name="win.add", css_classes=["pill", "suggested-action"])
        empty.set_child(add)

        # portfolio page
        self.summary = SummaryCard()
        self.groups = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24)
        self.footer = Gtk.Label(wrap=True, justify=Gtk.Justification.CENTER,
                                css_classes=["caption", "dim-label"])
        footer = self.footer
        content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24,
                          margin_top=18, margin_bottom=24, margin_start=12, margin_end=12)
        for w in (self.summary, self.groups, footer):
            content.append(w)
        scrolled = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER,
                                      child=Adw.Clamp(maximum_size=720, child=content))

        self.stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE)
        self.stack.add_named(empty, "empty")
        self.stack.add_named(scrolled, "portfolio")

        self.toasts = Adw.ToastOverlay(child=self.stack)
        toolbar = Adw.ToolbarView(content=self.toasts)
        toolbar.add_top_bar(header)
        # Explains when prices are saved values rather than current ones
        self.banner = Adw.Banner(button_label=_("_Retry"), action_name="win.refresh-now",
                                 revealed=False, use_markup=False)
        toolbar.add_top_bar(self.banner)
        self.set_content(toolbar)

        self._add_actions()
        self.connect("close-request", self._on_close_request)
        # charts pick red/green for the current light or dark style
        self._style_handler = Adw.StyleManager.get_default().connect(
            "notify::dark", lambda *_: self.render())
        self.refresh()
        self.render()
        self.reschedule()

    # ---- actions -----------------------------------------------------------

    def _build_menu(self):
        menu = Gio.Menu()
        currency = Gio.Menu()
        for code in BASE_CURRENCIES:
            currency.append(code, f"app.base-currency::{code}")
        section = Gio.Menu()
        section.append_submenu(_("Show Totals In"), currency)
        section.append(_("Refresh _Automatically"), "app.auto-refresh")
        menu.append_section(None, section)
        section = Gio.Menu()
        section.append(_("_Import from CSV…"), "win.import")
        section.append(_("_Export as CSV…"), "win.export")
        menu.append_section(None, section)
        section = Gio.Menu()
        section.append(_("_Preferences"), "app.preferences")
        section.append(_("_About Portfolio"), "app.about")
        menu.append_section(None, section)
        return menu

    def _add_actions(self):
        for name, callback in (("add", lambda *_: self.show_add_dialog()),
                               ("refresh", lambda *_: self.refresh(user=True)),
                               ("refresh-now", lambda *_: self.refresh(user=True, force=True)),
                               ("import", lambda *_: self.import_csv()),
                               ("export", lambda *_: self.export_csv()),
                               ("undo-remove", lambda *_: self.undo_remove())):
            action = Gio.SimpleAction.new(name, None)
            action.connect("activate", callback)
            self.add_action(action)

    # ---- data --------------------------------------------------------------

    @property
    def base_currency(self):
        return self.portfolio.settings["base_currency"]

    def rate_for(self, currency):
        return self.service.rate(currency, self.base_currency)

    def position_for(self, holding):
        return value_positions([holding], self.service.quotes, self.rate_for)[0]

    def refresh(self, user=False, force=False):
        if self.refreshing:
            return
        holdings = [(h.symbol, h.exchange, h.currency) for h in self.portfolio.holdings]
        if not holdings:
            self.render()
            return
        self.refreshing = True
        self.refresh_stack.set_visible_child_name("spinner")
        self._user_refresh = user
        self.service.refresh(holdings, self.base_currency, self._on_refreshed,
                             force=force or user)

    def _on_refreshed(self, result):
        self.refreshing = False
        self.refresh_stack.set_visible_child_name("button")
        self.last_result = result
        changed = False
        for h in self.portfolio.holdings:
            q = self.service.quotes.get(h.symbol)
            if not q:
                continue
            # Only Yahoo! reports full company names; fallbacks give the ticker
            if q.name and (q.source == "yahoo" or not h.name) and h.name != q.name:
                h.name, changed = q.name, True
            if q.currency and h.currency != q.currency:
                h.currency, changed = q.currency, True
        if changed:
            self._save()

        if self._user_refresh and not result.ok and not self._banner_reason():
            self.toasts.add_toast(Adw.Toast(title=_("Some prices could not be updated"),
                                            timeout=4))
        self._schedule_retry(result)
        self.render()

    def _schedule_retry(self, result):
        """After a rate limit, try again when the source said it would be ready."""
        if self._retry_timer:
            GLib.source_remove(self._retry_timer)
            self._retry_timer = 0
        if result.retry_at and self.portfolio.settings.get("auto_refresh"):
            delay = max(5, int(result.retry_at - time.time()) + 1)
            self._retry_timer = GLib.timeout_add_seconds(delay, self._on_retry_timer)

    def _on_retry_timer(self):
        self._retry_timer = 0
        self.refresh()
        return GLib.SOURCE_REMOVE

    def reschedule(self):
        if self._timer:
            GLib.source_remove(self._timer)
            self._timer = 0
        if self.portfolio.settings.get("auto_refresh"):
            interval = max(30, int(self.portfolio.settings.get("refresh_interval", 60)))
            self._timer = GLib.timeout_add_seconds(interval, self._on_timer)

    def _on_timer(self):
        if self.is_visible() and not self.is_suspended():
            self.refresh()
        return GLib.SOURCE_CONTINUE

    def set_base_currency(self, code):
        self.portfolio.settings["base_currency"] = code
        self.portfolio.save()
        self.render()
        self.refresh()

    def _save(self):
        try:
            self.portfolio.save()
        except OSError as e:
            self.toasts.add_toast(Adw.Toast(title=_("Could not save portfolio: {error}").format(
                error=e.strerror or str(e))))

    def add_holding(self, holding):
        h, merged = self.portfolio.add(holding)
        self.last_exchange = h.exchange
        self._save()
        self.render()
        title = (_("Added to your {symbol} position") if merged
                 else _("{symbol} added")).format(symbol=h.display_symbol)
        self.toasts.add_toast(Adw.Toast(title=title, timeout=3))
        if self.rate_for(h.currency) is None:
            self.refresh()

    def update_holding(self, holding_id, shares, cost):
        self.portfolio.update(holding_id, shares, cost)
        self._save()
        self.render()

    def remove_holding(self, holding_id):
        index, h = self.portfolio.remove(holding_id)
        if h is None:
            return
        self._undo = (index, h)
        self._save()
        self.render()
        toast = Adw.Toast(title=_("{symbol} removed").format(symbol=h.display_symbol),
                          button_label=_("_Undo"), action_name="win.undo-remove",
                          use_markup=False, timeout=6)
        self.toasts.add_toast(toast)

    def undo_remove(self):
        if not self._undo:
            return
        index, h = self._undo
        self._undo = None
        if self.portfolio.get(h.id) is None and self.portfolio.find_symbol(h.symbol) is None:
            self.portfolio.insert(index, h)
            self._save()
            self.render()

    # ---- presentation ------------------------------------------------------

    def render(self):
        holdings = self.portfolio.holdings
        if not holdings:
            self.stack.set_visible_child_name("empty")
            self.window_title.set_subtitle("")
            return
        self.stack.set_visible_child_name("portfolio")

        base = self.base_currency
        positions = value_positions(holdings, self.service.quotes, self.rate_for)
        summary = summarize(positions, base)
        self.summary.update(summary, self.refreshing)

        _clear(self.groups)
        for e in EXCHANGES:
            group_positions = [p for p in positions if p.holding.exchange == e.id]
            if not group_positions:
                continue
            group_positions.sort(key=lambda p: (p.value_base is None, -(p.value_base or 0),
                                                p.holding.display_symbol))
            group = Adw.PreferencesGroup(title=e.name)
            market_value = sum(p.market_value or 0 for p in group_positions
                               if p.currency == e.currency)
            group.set_description(ngettext("{n} holding · {value}", "{n} holdings · {value}",
                                           len(group_positions)).format(
                n=len(group_positions), value=formatting.money(market_value, e.currency, 0)))
            add = Gtk.Button(icon_name="list-add-symbolic", valign=Gtk.Align.CENTER,
                             tooltip_text=_("Add Stock on {exchange}").format(exchange=e.name),
                             css_classes=["flat"])
            add.connect("clicked", lambda _b, ex=e.id: self.show_add_dialog(ex))
            group.set_header_suffix(add)
            for p in group_positions:
                share = (p.value_base / summary.value
                         if p.value_base is not None and summary.value else None)
                row = PositionRow(p, base, share, self.service.is_stale(p.holding.symbol))
                row.connect("activated", self._on_row_activated)
                group.add(row)
            self.groups.append(group)

        self.window_title.set_subtitle(self._status_text())
        self.footer.set_label(self._footer_text())
        reason = self._banner_reason()
        if reason:
            self.banner.set_title(reason)
        self.banner.set_revealed(bool(reason))

        if self.detail is not None:
            self.detail.update()

    # ---- status texts ------------------------------------------------------

    def _held(self):
        return {h.symbol for h in self.portfolio.holdings}

    def _status_text(self):
        held = self._held()
        quotes = [self.service.quotes[s] for s in held if s in self.service.quotes]
        if not quotes:
            return _("Updating…") if self.refreshing else _("No prices yet")
        stale = held & self.service.stale
        if self.refreshing and stale == {q.symbol for q in quotes}:
            return _("Updating…")
        if stale:
            oldest = min(self.service.quotes[s].fetched_at for s in stale)
            return _("Saved prices · {time}").format(time=formatting.clock(oldest))
        newest = max(q.fetched_at for q in quotes)
        if all(q.delay_minutes == 0 for q in quotes):
            return _("Updated {time}").format(time=formatting.clock(newest))
        return _("Delayed · Updated {time}").format(time=formatting.clock(newest))

    def _footer_text(self):
        held = self._held()
        quotes = [self.service.quotes[s] for s in held if s in self.service.quotes]
        sources = sorted({q.source for q in quotes if q.source in PROVIDERS_BY_ID},
                         key=lambda pid: pid != self.service.primary)
        names = [PROVIDERS_BY_ID[pid].name for pid in sources] or \
            [self.service.primary_provider.name]
        delay = max((q.delay_minutes for q in quotes), default=15)
        if delay >= 24 * 60:
            delayed = _("some are end-of-day prices")
        elif delay > 0:
            delayed = _("delayed up to {n} minutes").format(n=delay)
        else:
            delayed = _("real-time")
        return _("Prices from {sources}, {delayed}. Return is in each stock's own currency, "
                 "converted at today's exchange rate.").format(
            sources=_(" and ").join(names), delayed=delayed)

    def _banner_reason(self):
        """Why some prices are saved or missing, or None when all is current."""
        r = self.last_result
        if r is None:
            return None
        held = self._held()
        stale = held & self.service.stale
        missing = held & r.missing
        if not stale and not missing:
            return None
        source = self.service.primary_provider.name
        if stale:
            oldest = min(self.service.quotes[s].fetched_at for s in stale)
            when = formatting.clock(oldest)
            if r.rate_limited:
                text = _("{source} is limiting requests. Showing saved prices from {time}.")
                if r.retry_at and self.portfolio.settings.get("auto_refresh"):
                    text += " " + _("Retrying at {retry}.").format(
                        retry=formatting.clock(r.retry_at))
                return text.format(source=source, time=when)
            if not r.updated and not r.reused:
                return _("Can't reach {source}. Showing saved prices from {time}.").format(
                    source=source, time=when)
            return ngettext("{n} price could not be updated and shows a saved value",
                            "{n} prices could not be updated and show saved values",
                            len(stale)).format(n=len(stale))
        return ngettext("No price available for {n} holding",
                        "No price available for {n} holdings",
                        len(missing)).format(n=len(missing))

    def _on_row_activated(self, row):
        self.detail = PositionDialog(self, row.holding_id)
        self.detail.connect("closed", self._on_detail_closed)
        self.detail.present(self)

    def _on_detail_closed(self, dialog):
        if self.detail is dialog:
            self.detail = None

    def show_add_dialog(self, exchange_id=None):
        HoldingDialog(self, exchange_id=exchange_id).present(self)

    # ---- import ------------------------------------------------------------

    def import_csv(self):
        dialog = Gtk.FileDialog(title=_("Import Portfolio"))
        csv_filter = Gtk.FileFilter(name=_("CSV Files"))
        csv_filter.add_mime_type("text/csv")
        csv_filter.add_suffix("csv")
        filters = Gio.ListStore.new(Gtk.FileFilter)
        filters.append(csv_filter)
        dialog.set_filters(filters)
        dialog.open(self, None, self._on_import_chosen)

    def _on_import_chosen(self, dialog, result):
        try:
            gfile = dialog.open_finish(result)
        except GLib.Error:
            return
        try:
            ok, contents, _etag = gfile.load_contents(None)
            text = contents.decode("utf-8") if isinstance(contents, bytes) \
                else bytes(contents).decode("utf-8")
        except (GLib.Error, UnicodeDecodeError) as e:
            self.toasts.add_toast(Adw.Toast(title=_("Could not read the file: {error}").format(
                error=getattr(e, "message", str(e)))))
            return
        self.import_text(text)

    def import_text(self, text):
        holdings, problems = parse_portfolio_csv(text)
        if not holdings:
            self.toasts.add_toast(Adw.Toast(
                title=problems[0] if problems else _("No holdings found in the file")))
            return
        existing = [h for h in holdings if self.portfolio.find_symbol(h.symbol)]
        if not existing:
            self._apply_import(holdings, problems, replace=False)
            return
        alert = Adw.AlertDialog(
            heading=ngettext("Import {n} Holding?", "Import {n} Holdings?",
                             len(holdings)).format(n=len(holdings)),
            body=ngettext("{n} of them is already in your portfolio. Replace it with the "
                          "imported shares and price, or add the imported shares to it?",
                          "{n} of them are already in your portfolio. Replace them with the "
                          "imported shares and prices, or add the imported shares to them?",
                          len(existing)).format(n=len(existing)))
        alert.add_response("cancel", _("_Cancel"))
        alert.add_response("add", _("_Add Shares"))
        alert.add_response("replace", _("_Replace"))
        alert.set_response_appearance("replace", Adw.ResponseAppearance.SUGGESTED)
        alert.set_default_response("replace")
        alert.set_close_response("cancel")
        alert.connect("response", lambda _a, response: response != "cancel" and
                      self._apply_import(holdings, problems, replace=(response == "replace")))
        alert.present(self)

    def _apply_import(self, holdings, problems, replace):
        for h in holdings:
            current = self.portfolio.find_symbol(h.symbol)
            if current and replace:
                current.shares, current.cost = h.shares, h.cost
                current.name = current.name or h.name
            else:
                self.portfolio.add(h)
        self._save()
        self.render()
        message = ngettext("{n} holding imported", "{n} holdings imported",
                           len(holdings)).format(n=len(holdings))
        if problems:
            message += " · " + ngettext("{n} row skipped", "{n} rows skipped",
                                        len(problems)).format(n=len(problems))
        self.toasts.add_toast(Adw.Toast(title=message, timeout=4))
        self.refresh(force=True)

    # ---- export ------------------------------------------------------------

    def export_csv(self):
        if not self.portfolio.holdings:
            self.toasts.add_toast(Adw.Toast(title=_("Nothing to export yet")))
            return
        dialog = Gtk.FileDialog(title=_("Export Portfolio"), initial_name="portfolio.csv")
        csv_filter = Gtk.FileFilter(name=_("CSV Files"))
        csv_filter.add_mime_type("text/csv")
        filters = Gio.ListStore.new(Gtk.FileFilter)
        filters.append(csv_filter)
        dialog.set_filters(filters)
        dialog.save(self, None, self._on_export_chosen)

    def _on_export_chosen(self, dialog, result):
        try:
            gfile = dialog.save_finish(result)
        except GLib.Error:
            return  # cancelled
        base = self.base_currency
        rows = [["Exchange", "Symbol", "Name", "Shares", "Average Price", "Currency",
                 "Price", "Market Value", f"Market Value ({base})", "Total Return",
                 "Total Return %", "Day Change %", "Source", "Price Time"]]
        for p in value_positions(self.portfolio.holdings, self.service.quotes, self.rate_for):
            h = p.holding

            def r(v, d=4):
                return "" if v is None else f"{v:.{d}f}"
            rows.append([get_exchange(h.exchange).short_name, h.display_symbol, h.name,
                         r(h.shares), r(h.cost), p.currency or "", r(p.price),
                         r(p.market_value, 2), r(p.value_base, 2), r(p.gain, 2),
                         r(p.gain_percent, 2), r(p.day_percent, 2),
                         p.quote.source if p.quote else "",
                         time.strftime("%Y-%m-%d %H:%M", time.localtime(p.quote.fetched_at))
                         if p.quote else ""])
        try:
            with open(gfile.get_path(), "w", newline="", encoding="utf-8") as f:
                csv.writer(f).writerows(rows)
        except (OSError, TypeError) as e:
            self.toasts.add_toast(Adw.Toast(title=_("Export failed: {error}").format(error=e)))
            return
        self.toasts.add_toast(Adw.Toast(title=_("Portfolio exported"), timeout=3))

    def _on_close_request(self, *_args):
        Adw.StyleManager.get_default().disconnect(self._style_handler)
        if self._retry_timer:
            GLib.source_remove(self._retry_timer)
            self._retry_timer = 0
        if self._timer:
            GLib.source_remove(self._timer)
            self._timer = 0
        return False
