"""Tests for trade_panorama.scanner."""
import json
import os
import tempfile
import unittest
from trade_panorama.scanner import find_data_files, scan, aggregate
from trade_panorama.model import UnifiedTrade, BotSummary


class TestFindDataFiles(unittest.TestCase):
    def test_finds_known_files(self):
        with tempfile.TemporaryDirectory() as d:
            # Create nested structure
            sub = os.path.join(d, "bot1", "data")
            os.makedirs(sub)
            path = os.path.join(sub, "pnl.json")
            with open(path, "w") as f:
                json.dump({"trades": []}, f)

            found = find_data_files(d)
            self.assertIn("pnl.json", found)
            self.assertEqual(found["pnl.json"], path)

    def test_ignores_unknown(self):
        with tempfile.TemporaryDirectory() as d:
            with open(os.path.join(d, "random.json"), "w") as f:
                json.dump({}, f)
            found = find_data_files(d)
            self.assertEqual(len(found), 0)

    def test_keeps_deepest(self):
        with tempfile.TemporaryDirectory() as d:
            shallow = os.path.join(d, "pnl.json")
            deep_dir = os.path.join(d, "a", "b")
            os.makedirs(deep_dir)
            deep = os.path.join(deep_dir, "pnl.json")

            for p in [shallow, deep]:
                with open(p, "w") as f:
                    json.dump({"trades": []}, f)

            found = find_data_files(d)
            self.assertEqual(found["pnl.json"], deep)


class TestScan(unittest.TestCase):
    def test_scan_with_files(self):
        with tempfile.TemporaryDirectory() as d:
            path = os.path.join(d, "pnl.json")
            with open(path, "w") as f:
                json.dump({"trades": []}, f)

            summaries = scan(d, files={"pnl.json": path})
            self.assertEqual(len(summaries), 1)
            self.assertEqual(summaries[0].name, "Crypto (MEXC)")

    def test_scan_bad_json(self):
        with tempfile.TemporaryDirectory() as d:
            path = os.path.join(d, "pnl.json")
            with open(path, "w") as f:
                f.write("not json")
            summaries = scan(d, files={"pnl.json": path})
            self.assertEqual(len(summaries), 0)


class TestAggregate(unittest.TestCase):
    def _make(self, name, pnls, capital=0, initial=0, n_open=0):
        trades = [UnifiedTrade(name, "X", "LONG", 100, 100 + p, p, "", "")
                  for p in pnls]
        from trade_panorama.model import OpenPosition
        opens = [OpenPosition(name, "Y", "LONG", 50, "") for _ in range(n_open)]
        return BotSummary(name, trades=trades, open_positions=opens,
                          capital=capital, initial_capital=initial)

    def test_aggregate(self):
        s1 = self._make("A", [5, -2, 3], capital=1100, initial=1000, n_open=1)
        s2 = self._make("B", [-1, 4], capital=500, initial=500, n_open=2)
        agg = aggregate([s1, s2])
        self.assertEqual(agg["bots"], 2)
        self.assertEqual(agg["total_trades"], 5)
        self.assertEqual(agg["total_wins"], 3)
        self.assertAlmostEqual(agg["win_rate"], 3 / 5)
        self.assertAlmostEqual(agg["total_pnl_pct"], 9.0)
        self.assertEqual(agg["open_positions"], 3)
        self.assertEqual(agg["total_capital"], 1600)
        self.assertAlmostEqual(agg["capital_pnl"], 100)

    def test_aggregate_empty(self):
        agg = aggregate([])
        self.assertEqual(agg["total_trades"], 0)
        self.assertEqual(agg["win_rate"], 0)


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