from pathlib import Path
import unittest

from app.market import MarketService
from app.market.models import InquiryRequest
from app.mock_data import LocalMockDataService, MockBatchRequest
from app.repository import RDFRepository


ROOT = Path(__file__).resolve().parents[1]
HAIER = "https://gesli.example/sample#Haier"


class MockDataTest(unittest.TestCase):
    def setUp(self):
        self.repository = RDFRepository(ROOT)
        self.market = MarketService(ROOT, self.repository)
        self.mock_data = LocalMockDataService(ROOT, self.repository, self.market)

    def test_catalog_exposes_local_domain_data(self):
        catalog = self.mock_data.catalog()

        self.assertEqual(catalog["summary"]["in_memory_triple_count"], 0)
        self.assertGreaterEqual(catalog["summary"]["customer_count"], 9)
        self.assertGreaterEqual(catalog["summary"]["quote_count"], 24)
        self.assertGreaterEqual(catalog["summary"]["strategy_count"], 5)
        self.assertTrue(any(row["destination"] == "印度那瓦舍瓦港" for row in catalog["routes"]))
        india_direct = next(row for row in catalog["quotes"] if row["quote_no"] == "SQ-MOCK-IN-NHAVA-DIRECT-001")
        self.assertEqual(india_direct["spot_space_status"], "可立即订舱")
        self.assertEqual(india_direct["spot_space_teu"], 18)

    def test_generated_batch_immediately_joins_recommendation_pool(self):
        before = self.market.recommend(InquiryRequest(customer=HAIER))
        result = self.mock_data.generate(MockBatchRequest(
            origin="青岛港",
            destination="印度那瓦舍瓦港",
            supplier_count=4,
            customer_count=2,
        ))
        after = self.market.recommend(InquiryRequest(
            customer=HAIER,
            destination="印度那瓦舍瓦港",
            requested_departure_date="2026-07-28",
            max_transit_days=30,
            target_amount=46000,
        ))

        self.assertGreater(result["added_triples"], 100)
        self.assertEqual(result["catalog"]["summary"]["in_memory_triple_count"], result["added_triples"])
        self.assertEqual(after["pipeline"]["discovered"], 7)
        self.assertEqual(result["catalog"]["summary"]["customer_count"], 11)
        self.assertTrue(any("印度航线Mock" in name for name in result["suppliers"]))

    def test_reset_discards_only_runtime_mock_data(self):
        baseline = self.repository.triple_count
        self.mock_data.generate(MockBatchRequest(
            origin="青岛港",
            destination="印度金奈港",
            supplier_count=1,
            customer_count=1,
        ))
        reset_catalog = self.mock_data.reset()

        self.assertEqual(self.repository.triple_count, baseline)
        self.assertEqual(reset_catalog["summary"]["in_memory_triple_count"], 0)
        self.assertFalse(any(row["runtime_mock"] for row in reset_catalog["quotes"]))


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