from __future__ import annotations

import tempfile
import unittest
from datetime import datetime
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo

from source_activity_runtime.models import ExtractionContext, SourceRequest
from source_activity_runtime.providers.drmobilev2 import DrMobileV2Provider
from source_activity_runtime.providers.friends import FriendsProvider
from source_activity_runtime.providers.friends1 import build_provider as build_friends1
from source_activity_runtime.providers.mega import build_provider as build_mega
from source_activity_runtime.providers.trend import build_provider as build_trend


class FakeResponse:
    def __init__(self, status_code: int, payload: Any) -> None:
        self.status_code = status_code
        self._payload = payload
        self.text = str(payload)

    def json(self) -> Any:
        return self._payload


class FakeFriendsSession:
    def __init__(self) -> None:
        self.posts: list[tuple[str, dict[str, Any]]] = []

    def post(self, url: str, **kwargs: Any) -> FakeResponse:
        self.posts.append((url, kwargs))
        if url.endswith("/api/customer/login"):
            return FakeResponse(200, {"data": {"token": "SECRET", "name": "test"}})
        if "offset=0" in url:
            return FakeResponse(200, {
                "PayOff": [
                    {
                        "movement_id": 11,
                        "pay_offs_id": 101,
                        "status": 1,
                        "value": "10.00",
                        "qty": "10.00",
                        "balance": "90.00",
                        "number": "0990000001",
                        "code": None,
                        "company": "كاش SYRIATEL",
                        "company_id": 109,
                        "reply_date": "2026-07-17 10:00:00",
                        "created_at": "2026-07-17 10:00:00",
                        "response_aljaby": "تمت عملية التعبئة بنجاح",
                    },
                    {
                        "movement_id": 12,
                        "pay_offs_id": 102,
                        "status": 1,
                        "value": "20.00",
                        "qty": "20.00",
                        "balance": "70.00",
                        "number": "0990000002",
                        "company": "كاش SYRIATEL",
                        "company_id": 109,
                        "created_at": "2026-07-17 12:00:00",
                    },
                ]
            })
        raise AssertionError(f"Unexpected Friends URL: {url}")


class FakeDrMobileSession:
    def __init__(self) -> None:
        self.gets: list[tuple[str, dict[str, Any]]] = []

    def get(self, url: str, **kwargs: Any) -> FakeResponse:
        self.gets.append((url, kwargs))
        params = kwargs.get("params") or {}
        page = int(params.get("page", 1))
        if url == "https://provider.example/v2/orders":
            return FakeResponse(404, {"error": "not found"})
        if url != "https://provider.example/api/v2/orders":
            raise AssertionError(f"Unexpected DrMobile URL: {url}")
        if page == 1:
            return FakeResponse(200, {
                "success": True,
                "data": {
                    "items": [
                        {
                            "id": 9002,
                            "local_id": "remote-uuid-2",
                            "status": "مكتمل",
                            "message": "done",
                            "product_name": "Product B",
                            "quantity": 2,
                            "unit_price": 5,
                            "total_price": 10,
                            "currency": "SYR",
                            "player_id": "PLAYER-9002",
                            "created_at": "2026-07-17T11:00:00+03:00",
                        },
                        {
                            "id": 9001,
                            "local_id": "remote-uuid-1",
                            "status": "مكتمل",
                            "message": "done",
                            "product_name": "Product A",
                            "quantity": 1,
                            "unit_price": 5,
                            "total_price": 5,
                            "currency": "SYR",
                            "created_at": "2026-07-17T10:00:00+03:00",
                        },
                    ],
                    "pagination": {"page": 1, "per_page": 200, "total": 3, "last_page": 2},
                },
                "error": None,
            })
        if page == 2:
            return FakeResponse(200, {
                "success": True,
                "data": {
                    "items": [
                        {
                            "id": 8999,
                            "local_id": "remote-uuid-old",
                            "status": "مكتمل",
                            "message": "old",
                            "product_name": "Old",
                            "quantity": 1,
                            "total_price": 1,
                            "currency": "SYR",
                            "created_at": "2026-07-17T08:59:59+03:00",
                        }
                    ],
                    "pagination": {"page": 2, "per_page": 200, "total": 3, "last_page": 2},
                },
                "error": None,
            })
        raise AssertionError(f"Unexpected DrMobile page: {page}")


def make_context(root: Path, source: str, credentials: dict[str, Any], provider_options: dict[str, Any]) -> ExtractionContext:
    tz = ZoneInfo("Asia/Damascus")
    source_directory = root / source
    source_directory.mkdir(parents=True, exist_ok=True)
    return ExtractionContext(
        job_id="test-job",
        audit_run_id="test-audit",
        period_from=datetime(2026, 7, 17, 9, 0, 0, tzinfo=tz),
        period_to=datetime(2026, 7, 17, 12, 0, 0, tzinfo=tz),
        source=SourceRequest(
            source=source,
            source_account_key="a" * 64,
            service_source_id=1,
            credential_id=2,
            account_label="test",
            credentials=credentials,
            provider_options=provider_options,
        ),
        source_directory=source_directory,
        checkpoint_path=root / "checkpoint.json",
    )


class ReadyProviderTests(unittest.TestCase):
    def test_friends_exact_half_open_period_and_stable_ids(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            provider = FriendsProvider(session=FakeFriendsSession())
            context = make_context(
                Path(tmp),
                "friends",
                {"username": "u", "password": "p"},
                {"currency_code": "SYR", "request_options": {"offset_step": 50}},
            )
            records = list(provider.iter_records(context))
            self.assertTrue(provider.result_metadata()["coverage_verified"])
            self.assertTrue(provider.result_metadata()["zero_records_authoritative"])
            self.assertEqual(1, len(records))
            record = records[0]
            self.assertEqual("payoff:101", record.provider_record_key)
            self.assertEqual("101", record.provider_transaction_id)
            self.assertEqual("11", record.provider_reference)
            self.assertEqual("0990000001", record.subscriber_identifier)
            self.assertEqual("10.00", record.amount)
            self.assertEqual("10.00", record.cost_amount)
            self.assertEqual("completed", record.provider_status)
            self.assertEqual(
                "0990000001",
                record.raw_payload["reconciliation_identifiers"]["phone"],
            )

    def test_drmobile_pagination_cutoff_and_identifiers(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            provider = DrMobileV2Provider(session=FakeDrMobileSession())
            context = make_context(
                Path(tmp),
                "drmobilev2",
                {"api_token": "TOKEN"},
                {"base_url": "https://provider.example", "currency_code": "SYR"},
            )
            records = list(provider.iter_records(context))
            self.assertTrue(provider.result_metadata()["coverage_verified"])
            self.assertTrue(provider.result_metadata()["zero_records_authoritative"])
            self.assertEqual(["order:9002", "order:9001"], [r.provider_record_key for r in records])
            self.assertEqual(["9002", "9001"], [r.provider_transaction_id for r in records])
            self.assertEqual(["remote-uuid-2", "remote-uuid-1"], [r.provider_reference for r in records])
            self.assertEqual([10, 5], [r.cost_amount for r in records])
            self.assertEqual(
                "PLAYER-9002",
                records[0].raw_payload["reconciliation_identifiers"]["player_id"],
            )

    def test_alias_modules_build_verified_implementations(self) -> None:
        self.assertIsInstance(build_friends1(), FriendsProvider)
        self.assertIsInstance(build_trend(), DrMobileV2Provider)
        self.assertIsInstance(build_mega(), DrMobileV2Provider)


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