from pathlib import Path
from types import SimpleNamespace

from mbetterclient.api_client.client import ReportsSyncResponseHandler
from mbetterclient.core.message_bus import MessageBus
from mbetterclient.database.manager import DatabaseManager
from mbetterclient.database.models import BetDetailModel, BetModel


def _build_handler(tmp_path: Path):
    db_path = tmp_path / "reports_sync_summary.db"
    db_manager = DatabaseManager(str(db_path))
    assert db_manager.initialize()
    handler = ReportsSyncResponseHandler(
        db_manager=db_manager,
        user_data_dir=str(tmp_path),
        api_client=SimpleNamespace(settings=SimpleNamespace(rustdesk_id=None)),
        message_bus=MessageBus(),
    )
    return handler, db_manager


def test_calculate_summary_uses_settled_rows_and_unique_matches(tmp_path):
    handler, db_manager = _build_handler(tmp_path)
    session = db_manager.get_session()
    try:
        bet = BetModel(uuid='bet-1', fixture_id='fixture-1', paid=True, paid_out=False)
        session.add(bet)
        session.flush()
        session.add_all([
            BetDetailModel(bet_id='bet-1', match_id=10, match_number=1, outcome='UNDER', amount=10.0, win_amount=20.0, result='win'),
            BetDetailModel(bet_id='bet-1', match_id=10, match_number=1, outcome='OVER', amount=15.0, win_amount=0.0, result='lost'),
            BetDetailModel(bet_id='bet-1', match_id=11, match_number=2, outcome='WIN1', amount=25.0, win_amount=75.0, result='win'),
            BetDetailModel(bet_id='bet-1', match_id=11, match_number=2, outcome='KO1', amount=5.0, win_amount=0.0, result='cancelled'),
        ])
        session.commit()

        loaded_bet = session.query(BetModel).filter_by(uuid='bet-1').first()
        summary = handler._calculate_summary([loaded_bet], stats=[])

        assert summary['total_payin'] == 50.0
        assert summary['total_payout'] == 95.0
        assert summary['net_profit'] == -45.0
        assert summary['total_bets'] == 3
        assert summary['total_matches'] == 2
    finally:
        session.close()
        db_manager.close()


def test_calculate_summary_payload_can_carry_global_balance_separately(tmp_path):
    handler, db_manager = _build_handler(tmp_path)
    try:
        summary = handler._calculate_summary([], stats=[])
        assert summary['total_payin'] == 0.0
        assert summary['total_payout'] == 0.0
        assert summary['total_matches'] == 0
    finally:
        db_manager.close()
