from __future__ import annotations

import gzip
import json
import tempfile
import threading
import unittest
from datetime import datetime, timezone, timedelta
from pathlib import Path

from source_activity_runtime.models import ExtractionContext, ProviderRecord
from source_activity_runtime.provider import SourceActivityProvider
from source_activity_runtime.registry import clear_testing_registry, register_for_testing
from source_activity_runtime.runner import run_extraction


class FakeProvider(SourceActivityProvider):
    def iter_records(self, context: ExtractionContext):
        for index in range(7):
            yield ProviderRecord(
                provider_record_key=f"tx-{index}",
                occurred_at=context.period_from + timedelta(minutes=index + 1),
                record_type="customer_payment",
                provider_status="completed",
                provider_transaction_id=f"TX{index}",
                subscriber_identifier=f"01100000{index:02d}",
                amount="100.00",
                currency="SYP",
                raw_payload={"id": index},
            )


class OutsidePeriodProvider(SourceActivityProvider):
    def iter_records(self, context: ExtractionContext):
        yield ProviderRecord(
            provider_record_key="outside",
            occurred_at=context.period_to,
            record_type="customer_payment",
            provider_status="completed",
        )


class ParallelProvider(SourceActivityProvider):
    barrier = threading.Barrier(4)

    def iter_records(self, context: ExtractionContext):
        self.barrier.wait(timeout=2)
        yield ProviderRecord(
            provider_record_key=f"parallel-{context.source.credential_id}",
            occurred_at=context.period_from + timedelta(minutes=1),
            record_type="customer_payment",
            provider_status="completed",
        )


class RuntimeTest(unittest.TestCase):
    def tearDown(self):
        clear_testing_registry()

    def payload(self, root: Path, source: str = "fake"):
        return {
            "job_id": "audit-test-001",
            "audit_run_id": "audit-1",
            "from": "2026-07-12T00:00:00+03:00",
            "to": "2026-07-13T00:00:00+03:00",
            "storage_root": str(root),
            "part_records": 3,
            "sources": [{
                "source": source,
                "service_source_id": 12,
                "credential_id": 7,
                "credentials": {"username": "user", "password": "secret"},
            }],
        }

    def test_streaming_parts_and_sanitization(self):
        register_for_testing("fake", FakeProvider)
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            result = run_extraction(self.payload(root))
            self.assertTrue(result["ok"])
            manifest = json.loads(Path(result["manifest_path"]).read_text(encoding="utf-8"))
            source = manifest["sources"][0]
            self.assertEqual(source["record_count"], 7)
            self.assertEqual(len(source["parts"]), 3)
            count = 0
            for part in source["parts"]:
                with gzip.open(root / part["relative_path"], "rt", encoding="utf-8") as handle:
                    count += sum(1 for _ in handle)
            self.assertEqual(count, 7)
            sanitized = next(root.rglob("request.sanitized.json")).read_text(encoding="utf-8")
            self.assertNotIn("secret", sanitized)
            self.assertIn("[REDACTED]", sanitized)

    def test_missing_provider_is_note_not_fake_data(self):
        with tempfile.TemporaryDirectory() as tmp:
            result = run_extraction(self.payload(Path(tmp), source="missing_provider"))
            manifest = json.loads(Path(result["manifest_path"]).read_text(encoding="utf-8"))
            self.assertEqual(manifest["sources"][0]["status"], "not_implemented")
            self.assertEqual(manifest["sources"][0]["record_count"], 0)

    def test_outside_period_marks_source_failed(self):
        register_for_testing("outside", OutsidePeriodProvider)
        with tempfile.TemporaryDirectory() as tmp:
            result = run_extraction(self.payload(Path(tmp), source="outside"))
            manifest = json.loads(Path(result["manifest_path"]).read_text(encoding="utf-8"))
            self.assertEqual(manifest["sources"][0]["status"], "failed")
            self.assertIn("outside", manifest["sources"][0]["error_message"])

    def test_sources_run_in_parallel_and_manifest_order_is_stable(self):
        register_for_testing("parallel", ParallelProvider)
        with tempfile.TemporaryDirectory() as tmp:
            payload = self.payload(Path(tmp), source="parallel")
            payload["max_workers"] = 4
            payload["sources"] = [
                {
                    "source": "parallel",
                    "service_source_id": 12,
                    "credential_id": credential_id,
                    "credentials": {},
                }
                for credential_id in [4, 2, 7, 1]
            ]
            result = run_extraction(payload)
            manifest = json.loads(Path(result["manifest_path"]).read_text(encoding="utf-8"))
            self.assertEqual(manifest["execution"]["workers_used"], 4)
            self.assertEqual(
                [source["credential_id"] for source in manifest["sources"]],
                [4, 2, 7, 1],
            )
            self.assertTrue(all(source["status"] == "completed" for source in manifest["sources"]))


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