# model.py — holdings, persistence and valuation
#
# SPDX-License-Identifier: GPL-3.0-or-later

import json
import os
import uuid
from dataclasses import asdict, dataclass, field
from datetime import date
from pathlib import Path

from .exchanges import EXCHANGES, BASE_CURRENCIES, display_symbol

DEFAULT_SETTINGS = {
    "base_currency": "NOK",
    "auto_refresh": True,
    "refresh_interval": 60,
    "data_source": "yahoo",
    "use_fallbacks": True,
    # API keys live in the GNOME keyring when available; this is the fallback
    "api_keys": {},
}

# An average price this far from the market price is probably a typo or the
# wrong currency (e.g. NOK typed for a USD stock).
SUSPICIOUS_PRICE_RATIO = 20.0


def data_dir():
    base = os.environ.get("XDG_DATA_HOME") or os.path.join(Path.home(), ".local", "share")
    return Path(base) / "gnome-portfolio"


@dataclass
class Holding:
    symbol: str            # Yahoo symbol, e.g. "EQNR.OL"
    exchange: str          # "NYSE", "STO" or "OSL"
    shares: float
    cost: float            # average price paid per share, in the listing currency
    name: str = ""
    currency: str = ""
    id: str = field(default_factory=lambda: uuid.uuid4().hex)
    added: str = field(default_factory=lambda: date.today().isoformat())

    @property
    def display_symbol(self):
        return display_symbol(self.symbol, self.exchange)

    @property
    def cost_basis(self):
        return self.shares * self.cost

    def to_dict(self):
        return asdict(self)

    @classmethod
    def from_dict(cls, d):
        known = {k: d[k] for k in cls.__dataclass_fields__ if k in d}
        known["shares"] = float(known.get("shares", 0))
        known["cost"] = float(known.get("cost", 0))
        return cls(**known)


class Portfolio:
    VERSION = 1

    def __init__(self, path=None):
        self.path = Path(path) if path else data_dir() / "portfolio.json"
        self.holdings = []
        self.settings = dict(DEFAULT_SETTINGS, api_keys={})

    # ---- persistence ---------------------------------------------------

    def load(self):
        if not self.path.exists():
            return self
        try:
            doc = json.loads(self.path.read_text(encoding="utf-8"))
            holdings = [Holding.from_dict(h) for h in doc.get("holdings", [])]
            settings = doc.get("settings", {})
        except (OSError, ValueError, TypeError, KeyError):
            # Keep the broken file for inspection and start fresh
            self.path.replace(self.path.with_suffix(".json.corrupt"))
            return self
        self.holdings = holdings
        self.settings.update({k: v for k, v in settings.items() if k in DEFAULT_SETTINGS})
        if self.settings["base_currency"] not in BASE_CURRENCIES:
            self.settings["base_currency"] = DEFAULT_SETTINGS["base_currency"]
        return self

    def save(self):
        self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        doc = {
            "version": self.VERSION,
            "settings": self.settings,
            "holdings": [h.to_dict() for h in self.holdings],
        }
        tmp = self.path.with_suffix(".json.tmp")
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(json.dumps(doc, indent=2, ensure_ascii=False))
        os.replace(tmp, self.path)

    # ---- editing -------------------------------------------------------

    def get(self, holding_id):
        return next((h for h in self.holdings if h.id == holding_id), None)

    def find_symbol(self, symbol):
        return next((h for h in self.holdings if h.symbol == symbol), None)

    def add(self, holding):
        """Add a holding. Buying more of a stock already held merges the lots
        using a share-weighted average price. Returns (holding, merged)."""
        existing = self.find_symbol(holding.symbol)
        if existing is None:
            self.holdings.append(holding)
            return holding, False
        total = existing.shares + holding.shares
        if total > 0:
            existing.cost = (existing.cost_basis + holding.cost_basis) / total
        existing.shares = total
        existing.name = holding.name or existing.name
        existing.currency = holding.currency or existing.currency
        return existing, True

    def insert(self, index, holding):
        self.holdings.insert(min(index, len(self.holdings)), holding)

    def update(self, holding_id, shares, cost):
        h = self.get(holding_id)
        if h:
            h.shares, h.cost = shares, cost
        return h

    def remove(self, holding_id):
        for i, h in enumerate(self.holdings):
            if h.id == holding_id:
                del self.holdings[i]
                return i, h
        return None, None

    def symbols(self):
        return [h.symbol for h in self.holdings]


# ---- valuation ---------------------------------------------------------

@dataclass
class Position:
    holding: Holding
    quote: object = None          # quotes.Quote or None
    rate: float | None = None     # listing currency -> base currency

    @property
    def currency(self):
        return (self.quote.currency if self.quote else None) or self.holding.currency

    @property
    def price(self):
        return self.quote.price if self.quote else None

    @property
    def market_value(self):
        return None if self.price is None else self.price * self.holding.shares

    @property
    def gain(self):
        mv = self.market_value
        return None if mv is None else mv - self.holding.cost_basis

    @property
    def gain_percent(self):
        if self.gain is None or not self.holding.cost_basis:
            return None
        return self.gain / self.holding.cost_basis * 100.0

    @property
    def day_change(self):
        if not self.quote or self.quote.change is None:
            return None
        return self.quote.change * self.holding.shares

    @property
    def day_percent(self):
        return self.quote.change_percent if self.quote else None

    def _base(self, value):
        if value is None or self.rate is None:
            return None
        return value * self.rate

    @property
    def value_base(self):
        return self._base(self.market_value)

    @property
    def cost_base(self):
        # Converted at today's rate: the return shown is in the stock's own currency
        return self._base(self.holding.cost_basis)

    @property
    def gain_base(self):
        return self._base(self.gain)

    @property
    def day_change_base(self):
        return self._base(self.day_change)


@dataclass
class Summary:
    base_currency: str
    value: float = 0.0
    cost: float = 0.0
    day_change: float = 0.0
    priced: int = 0
    missing: int = 0
    by_exchange: dict = field(default_factory=dict)

    @property
    def gain(self):
        return self.value - self.cost

    @property
    def gain_percent(self):
        return self.gain / self.cost * 100.0 if self.cost else None

    @property
    def day_percent(self):
        start = self.value - self.day_change
        return self.day_change / start * 100.0 if start else None

    def allocation(self):
        """[(exchange, fraction)] in exchange order, skipping empty markets."""
        if self.value <= 0:
            return []
        return [(e, self.by_exchange[e.id] / self.value)
                for e in EXCHANGES if self.by_exchange.get(e.id, 0) > 0]


def value_positions(holdings, quotes, rate_for):
    """rate_for(currency) -> float | None"""
    positions = []
    for h in holdings:
        q = quotes.get(h.symbol)
        currency = (q.currency if q else None) or h.currency
        positions.append(Position(h, q, rate_for(currency) if currency else None))
    return positions


def summarize(positions, base_currency):
    s = Summary(base_currency)
    for p in positions:
        if p.value_base is None:
            s.missing += 1
            continue
        s.priced += 1
        s.value += p.value_base
        s.cost += p.cost_base
        s.day_change += p.day_change_base or 0.0
        ex = p.holding.exchange
        s.by_exchange[ex] = s.by_exchange.get(ex, 0.0) + p.value_base
    return s


def price_looks_wrong(average_price, market_price):
    """True when an average price is implausibly far from the market price."""
    if not average_price or not market_price or average_price <= 0 or market_price <= 0:
        return False
    ratio = max(average_price, market_price) / min(average_price, market_price)
    return ratio >= SUSPICIOUS_PRICE_RATIO


# ---- CSV import ----------------------------------------------------------

def _exchange_from_text(text):
    t = (text or "").strip().lower()
    for e in EXCHANGES:
        if t in {e.id.lower(), e.short_name.lower(), e.name.lower(),
                 e.suffix.lower().lstrip(".")} - {""}:
            return e.id
    aliases = {"oslo børs": "OSL", "oslo bors": "OSL", "ose": "OSL", "xosl": "OSL",
               "stockholm": "STO", "xsto": "STO", "nasdaq stockholm": "STO",
               "nyse": "NYSE", "xnys": "NYSE", "new york": "NYSE"}
    return aliases.get(t)


def parse_portfolio_csv(text):
    """Read a portfolio CSV, such as one exported by Portfolio.

    Needs Exchange, Symbol, Shares and Average Price columns (names are
    matched case-insensitively; Name and Currency are optional). Returns
    (holdings, problems) where problems are human-readable row notes.
    """
    import csv
    import io

    from .exchanges import detect_exchange, to_yahoo_symbol
    from .formatting import parse_decimal

    reader = csv.DictReader(io.StringIO(text.lstrip("\ufeff")))
    columns = {c.strip().lower(): c for c in reader.fieldnames or []}

    def col(row, *names):
        for n in names:
            if n in columns:
                return (row.get(columns[n]) or "").strip()
        return ""

    if "symbol" not in columns or "shares" not in columns:
        return [], ["The file needs at least Symbol and Shares columns"]

    holdings, problems = [], []
    for line, row in enumerate(reader, start=2):
        symbol_text = col(row, "symbol", "ticker")
        if not symbol_text:
            continue
        exchange = _exchange_from_text(col(row, "exchange", "market")) or \
            detect_exchange(symbol_text)
        if not exchange:
            problems.append(f"Row {line}: unknown exchange for {symbol_text}")
            continue
        shares = parse_decimal(col(row, "shares", "quantity"))
        cost = parse_decimal(col(row, "average price", "avg price", "cost", "price paid"))
        if not shares:
            problems.append(f"Row {line}: no number of shares for {symbol_text}")
            continue
        holdings.append(Holding(
            symbol=to_yahoo_symbol(symbol_text, exchange), exchange=exchange,
            shares=shares, cost=cost or 0.0, name=col(row, "name"),
            currency=col(row, "currency").upper()))
    return holdings, problems
