# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for the GTK-free parts: exchanges, quote parsing, FX, storage, valuation."""

import json
import tempfile
import unittest
from pathlib import Path

from gnome_portfolio import exchanges, formatting
from gnome_portfolio.model import Holding, Portfolio, summarize, value_positions
from gnome_portfolio.quotes import Quote, QuoteError, parse_chart


def chart(symbol, price, prev, currency, code, closes=(1.0, None, 2.0), name=None):
    return {"chart": {"error": None, "result": [{
        "meta": {"symbol": symbol, "currency": currency, "regularMarketPrice": price,
                 "chartPreviousClose": prev, "exchangeName": code,
                 "fullExchangeName": code + " full", "longName": name or symbol + " ASA",
                 "regularMarketTime": 1762100000},
        "timestamp": [1, 2, 3],
        "indicators": {"quote": [{"close": list(closes)}]},
    }]}}


class ExchangeTests(unittest.TestCase):
    def test_symbols(self):
        self.assertEqual(exchanges.to_yahoo_symbol(" eqnr ", "OSL"), "EQNR.OL")
        self.assertEqual(exchanges.to_yahoo_symbol("EQNR.OL", "OSL"), "EQNR.OL")
        self.assertEqual(exchanges.to_yahoo_symbol("volv b", "STO"), "VOLV-B.ST")
        self.assertEqual(exchanges.to_yahoo_symbol("brk.b", "NYSE"), "BRK-B")
        self.assertEqual(exchanges.to_yahoo_symbol("  ", "NYSE"), "")
        self.assertEqual(exchanges.display_symbol("ERIC-B.ST", "STO"), "ERIC-B")
        self.assertEqual(exchanges.detect_exchange("dnb.ol"), "OSL")
        self.assertEqual(exchanges.detect_exchange("KO"), None)

    def test_listing_check(self):
        nasdaq = Quote("AAPL", "Apple", "USD", 1, 1, "NMS", "NasdaqGS")
        self.assertIn("NasdaqGS", exchanges.listing_problem(nasdaq, "NYSE"))
        ko = Quote("KO", "Coca-Cola", "USD", 1, 1, "NYQ", "NYSE")
        self.assertIsNone(exchanges.listing_problem(ko, "NYSE"))


class ParseTests(unittest.TestCase):
    def test_parse(self):
        q = parse_chart(chart("EQNR.OL", 250.0, 245.0, "NOK", "OSL"))
        self.assertEqual(q.currency, "NOK")
        self.assertEqual(q.points, [(1, 1.0), (3, 2.0)])
        self.assertAlmostEqual(q.change, 5.0)
        self.assertAlmostEqual(q.change_percent, 5 / 245 * 100)
        self.assertEqual(q.name, "EQNR.OL ASA")

    def test_minor_units(self):
        q = parse_chart(chart("BP.L", 450.0, 440.0, "GBp", "LSE", closes=(400.0,)))
        self.assertEqual(q.currency, "GBP")
        self.assertAlmostEqual(q.price, 4.5)
        self.assertEqual(q.points, [(1, 4.0)])

    def test_errors(self):
        with self.assertRaises(QuoteError):
            parse_chart({"chart": {"result": None, "error": {
                "code": "Not Found", "description": "No data found, symbol may be delisted"}}})
        with self.assertRaises(QuoteError):
            parse_chart({"chart": {"result": [], "error": None}})


class PortfolioTests(unittest.TestCase):
    def test_merge_save_load(self):
        with tempfile.TemporaryDirectory() as d:
            p = Portfolio(Path(d) / "p.json")
            p.add(Holding("EQNR.OL", "OSL", 10, 200.0, "Equinor", "NOK"))
            h, merged = p.add(Holding("EQNR.OL", "OSL", 30, 240.0, "Equinor", "NOK"))
            self.assertTrue(merged)
            self.assertEqual(h.shares, 40)
            self.assertAlmostEqual(h.cost, 230.0)
            p.add(Holding("KO", "NYSE", 5, 60.0, "Coca-Cola", "USD"))
            p.settings["base_currency"] = "SEK"
            p.save()
            q = Portfolio(Path(d) / "p.json").load()
            self.assertEqual([x.symbol for x in q.holdings], ["EQNR.OL", "KO"])
            self.assertEqual(q.settings["base_currency"], "SEK")
            idx, removed = q.remove(q.holdings[0].id)
            self.assertEqual((idx, removed.symbol), (0, "EQNR.OL"))

    def test_corrupt_file(self):
        with tempfile.TemporaryDirectory() as d:
            path = Path(d) / "p.json"
            path.write_text("{not json")
            p = Portfolio(path).load()
            self.assertEqual(p.holdings, [])
            self.assertTrue(path.with_suffix(".json.corrupt").exists())

    def test_valuation(self):
        holdings = [Holding("KO", "NYSE", 10, 60.0, currency="USD"),
                    Holding("EQNR.OL", "OSL", 100, 200.0, currency="NOK"),
                    Holding("GONE.ST", "STO", 1, 1.0, currency="SEK")]
        quotes = {"KO": Quote("KO", "KO", "USD", 70.0, 69.0),
                  "EQNR.OL": Quote("EQNR.OL", "EQNR", "NOK", 250.0, 260.0)}
        rates = {"NOK": 1.0, "USD": 10.0}
        positions = value_positions(holdings, quotes, rates.get)
        s = summarize(positions, "NOK")
        self.assertAlmostEqual(s.value, 700 * 10 + 25000)
        self.assertAlmostEqual(s.cost, 600 * 10 + 20000)
        self.assertAlmostEqual(s.day_change, 10 * 10 - 1000)
        self.assertAlmostEqual(s.day_percent, -900 / (32000 + 900) * 100)
        self.assertEqual((s.priced, s.missing), (2, 1))
        alloc = dict((e.id, f) for e, f in s.allocation())
        self.assertAlmostEqual(alloc["NYSE"] + alloc["OSL"], 1.0)
        self.assertAlmostEqual(positions[0].gain_percent, 100 / 600 * 100)


OLE_CSV = """Exchange,Symbol,Name,Shares,Average Price,Currency,Price,Market Value,Market Value (NOK),Total Return,Total Return %,Day Change %
Oslo,NAS,Norwegian Air Shuttle ASA,50.0000,11.6750,NOK,11.6750,583.75,583.75,0.00,0.00,3.73
NYSE,GM,General Motors Company,50.0000,0.0928,USD,89.3000,4465.00,41523.61,4460.36,96128.45,2.17
Stockholm,VOLV-B,AB Volvo (publ),50.0000,309.0000,SEK,309.0000,15450.00,14677.50,0.00,0.00,-0.32
"""


class ImportTests(unittest.TestCase):
    def test_portfolio_export(self):
        from gnome_portfolio.model import parse_portfolio_csv
        holdings, problems = parse_portfolio_csv(OLE_CSV)
        self.assertEqual(problems, [])
        self.assertEqual([(h.symbol, h.exchange, h.shares, h.cost, h.currency) for h in holdings],
                         [("NAS.OL", "OSL", 50, 11.675, "NOK"), ("GM", "NYSE", 50, 0.0928, "USD"),
                          ("VOLV-B.ST", "STO", 50, 309.0, "SEK")])

    def test_minimal_and_bad_rows(self):
        from gnome_portfolio.model import parse_portfolio_csv
        holdings, problems = parse_portfolio_csv(
            "\ufeffsymbol;x\n".replace(";", ",") + "EQNR.OL,1\n")
        self.assertEqual(holdings, [])          # no Shares column
        holdings, problems = parse_portfolio_csv(
            "Symbol,Shares,Exchange\nEQNR.OL,10,\nKO,,NYSE\nFOO,3,Tokyo\nDNB,\"1 000,5\",OSE\n")
        self.assertEqual([(h.symbol, h.shares) for h in holdings],
                         [("EQNR.OL", 10), ("DNB.OL", 1000.5)])
        self.assertEqual(len(problems), 2)

    def test_price_check(self):
        from gnome_portfolio.model import price_looks_wrong
        self.assertTrue(price_looks_wrong(0.0928, 89.30))      # GM in the CSV above
        self.assertFalse(price_looks_wrong(8.93, 89.30))       # a 10-bagger is plausible
        self.assertTrue(price_looks_wrong(2000.0, 89.30))      # 22x above market
        self.assertFalse(price_looks_wrong(60.0, 89.30))
        self.assertFalse(price_looks_wrong(0, 89.30))


class FormattingTests(unittest.TestCase):
    def test_parse(self):
        self.assertEqual(formatting.parse_decimal("1 234,5"), 1234.5)
        self.assertEqual(formatting.parse_decimal("1,234.5"), 1234.5)
        self.assertEqual(formatting.parse_decimal("1.234,5"), 1234.5)
        self.assertEqual(formatting.parse_decimal("12.5"), 12.5)
        self.assertIsNone(formatting.parse_decimal("-3"))
        self.assertIsNone(formatting.parse_decimal("abc"))
        self.assertIsNone(formatting.parse_decimal("nan"))

    def test_format(self):
        self.assertEqual(formatting.percent(1.234), "+1.23 %")
        self.assertEqual(formatting.signed_money(-5, "NOK"), "−5.00 NOK")
        self.assertEqual(formatting.shares(2.5), "2.5")
        self.assertEqual(formatting.shares(3.0), "3")
        self.assertEqual(formatting.price(0.1234), "0.1234")


if __name__ == "__main__":
    unittest.main()
