import json
import uuid
from datetime import date, time
from urllib.parse import unquote, urlparse

from asgiref.sync import async_to_sync
from asgiref.testing import ApplicationCommunicator
from django.test import TransactionTestCase
from rest_framework.test import APIClient

from apps.accounting.models import Account, Department, EmployeeProfile, Party, Voucher
from apps.accounting.services.core import VoucherService
from apps.accounts_rbac.constants import ROLE_PRESETS, Permissions
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.chat.services import DirectMessageService, TeamChannelService
from apps.hr.models import EmployeeDetail
from apps.localization.bs_calendar import bs_to_ad
from apps.notifications.consumers import NotificationWebsocketConsumer
from apps.notifications.models import (
    ConfirmationAudit,
    Notification,
    NotificationDelivery,
    NotificationEvent,
    NotificationPreference,
    NotificationRecipientState,
)
from apps.notifications.services import DomainEventService, broadcast_notification_force_disconnect
from apps.projects.models import Project
from apps.tenancy.models import Company, FiscalYear


class WsHarness(ApplicationCommunicator):
    def __init__(self, application, path: str):
        parsed = urlparse(path)
        self.scope = {
            "type": "websocket",
            "path": unquote(parsed.path),
            "query_string": parsed.query.encode("utf-8"),
            "headers": [],
            "subprotocols": [],
        }
        super().__init__(application, self.scope)

    async def connect(self, timeout=2):
        await self.send_input({"type": "websocket.connect"})
        res = await self.receive_output(timeout)
        if res["type"] == "websocket.close":
            return (False, res.get("code", 1000))
        return (True, res.get("subprotocol"))

    async def receive_json_from(self, timeout=2):
        res = await self.receive_output(timeout)
        assert res["type"] == "websocket.send", f"Unexpected frame: {res}"
        return json.loads(res["text"])

    async def disconnect(self, code=1000, timeout=2):
        await self.send_input({"type": "websocket.disconnect", "code": code})
        await self.wait(timeout)


class EnterpriseGlobalNotificationTests(TransactionTestCase):
    """24-scenario acceptance & security test suite for Maya OS Global Notifications & Popups."""

    def setUp(self):
        self.roles = {
            code: Role.objects.create(
                code=code,
                name=spec["name"],
                description=spec["description"],
                permissions=spec["permissions"],
                is_system=True,
            )
            for code, spec in ROLE_PRESETS.items()
        }
        self.no_approver_role = Role.objects.create(
            code="CHAT_ONLY_STAFF",
            name="Basic Staff",
            description="No voucher approval right",
            permissions=[
                Permissions.NOTIFICATION_VIEW,
                Permissions.NOTIFICATION_ACTION_EXECUTE,
                Permissions.CHAT_VIEW,
                Permissions.CHAT_SEND,
                Permissions.CHAT_DM_CREATE,
                Permissions.VOUCHER_READ,
                Permissions.VOUCHER_CREATE,
                Permissions.VOUCHER_SUBMIT,
            ],
            is_system=False,
        )

        self.company = Company.objects.create(code="NOTIF1", name="Notif Test Co", base_currency="NPR")
        self.company_b = Company.objects.create(code="NOTIF2", name="Other Corp", base_currency="NPR")
        self.fy = FiscalYear.objects.create(
            company=self.company,
            name="2083/84",
            start_date=bs_to_ad(2083, 4, 1),
            end_date=bs_to_ad(2084, 3, 31),
            is_current=True,
        )
        self.fy.generate_nepal_periods(2083)

        self.dept = Department.objects.create(company=self.company, code="FIN", name="Finance")
        self.prj_a = Project.objects.create(company=self.company, code="PRJ-N1", name="Project North")

        self.admin = User.objects.create_user(username="n_admin", email="nadmin@c1.local", password="Password@123", full_name="N Admin")
        self.approver = User.objects.create_user(username="n_approver", email="napp@c1.local", password="Password@123", full_name="Finance Approver")
        self.maker = User.objects.create_user(username="n_maker", email="nmaker@c1.local", password="Password@123", full_name="Accountant Maker")
        self.outsider = User.objects.create_user(username="n_out", email="nout@c2.local", password="Password@123", full_name="Outsider")

        CompanyMembership.objects.create(user=self.admin, company=self.company, role=self.roles["COMPANY_ADMIN"], is_default=True)
        CompanyMembership.objects.create(user=self.approver, company=self.company, role=self.roles["FINANCE_DIRECTOR"], is_default=True)
        CompanyMembership.objects.create(user=self.maker, company=self.company, role=self.no_approver_role, is_default=True)
        CompanyMembership.objects.create(user=self.outsider, company=self.company_b, role=self.roles["COMPANY_ADMIN"], is_default=True)

        self.cash = Account.objects.create(company=self.company, code="1010", name="Cash", account_type=Account.AccountType.ASSET)
        self.exp = Account.objects.create(company=self.company, code="5010", name="Expense", account_type=Account.AccountType.EXPENSE)
        self.wage_acc = Account.objects.create(
            company=self.company, code="2035", name="Wages", account_type=Account.AccountType.LIABILITY, control_role=Account.ControlRole.WAGES_PAYABLE
        )
        for u, code, nm in [(self.approver, "E-10", "Finance Approver"), (self.maker, "E-11", "Accountant Maker")]:
            p = Party.objects.create(company=self.company, party_type="EMPLOYEE", code=code, name=nm, control_account=self.wage_acc)
            ep = EmployeeProfile.objects.create(company=self.company, party=p, employee_code=code, full_name=nm, department=self.dept)
            EmployeeDetail.objects.create(company=self.company, employee_profile=ep, user=u)

        self.voucher = VoucherService.create_draft(
            company=self.company,
            user=self.maker,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": date(2026, 11, 22), "project": self.prj_a},
            lines_data=[
                {"account": self.exp, "debit": 1200, "credit": 0, "description": "Cement"},
                {"account": self.cash, "debit": 0, "credit": 1200, "description": "Cash"},
            ],
        )

    def _client(self, user: User, comp: Company | None = None) -> APIClient:
        c = APIClient()
        c.force_authenticate(user=user)
        c.defaults["HTTP_X_COMPANY_ID"] = str((comp or self.company).id)
        return c

    def test_01_workflow_approval_routing_action_revalidation_and_stale_block(self):
        # Submit triggers voucher.approval_required AFTER commit ONLY to authorized approvers (not maker!)
        VoucherService.submit_voucher(voucher=self.voucher, user=self.maker)

        self.assertTrue(
            Notification.objects.filter(
                company=self.company, recipient=self.approver, event_type="voucher.approval_required"
            ).exists()
        )
        # Maker has no VOUCHER_APPROVE & is actor -> must not receive approval request
        self.assertFalse(
            Notification.objects.filter(
                company=self.company, recipient=self.maker, event_type="voucher.approval_required"
            ).exists()
        )
        self.assertFalse(
            Notification.objects.filter(recipient=self.outsider, event_type="voucher.approval_required").exists()
        )

        # Unauthorized user crafting execute-action on approver's notification -> 403
        notif_app = Notification.objects.get(recipient=self.approver, event_type="voucher.approval_required")
        c_maker = self._client(self.maker)
        self.assertEqual(
            c_maker.post(f"/api/notifications/{notif_app.id}/execute-action/", {"action_key": "APPROVE_VOUCHER"}, format="json").status_code,
            403,
        )

        # Approver executes APPROVE_VOUCHER -> approves voucher, records audit, sends voucher.approved to maker
        c_app = self._client(self.approver)
        exec_res = c_app.post(
            f"/api/notifications/{notif_app.id}/execute-action/",
            {"action_key": "APPROVE_VOUCHER", "comment": "Looks balanced"},
            format="json",
        )
        self.assertEqual(exec_res.status_code, 200)
        self.assertEqual(exec_res.data["voucher_status"], "APPROVED")
        self.assertTrue(ConfirmationAudit.objects.filter(company=self.company, action_type="APPROVE_VOUCHER", actor=self.approver).exists())
        self.assertTrue(Notification.objects.filter(recipient=self.maker, event_type="voucher.approved").exists())

        # Re-executing stale notification fails cleanly with 409 Conflict
        stale_res = c_app.post(
            f"/api/notifications/{notif_app.id}/execute-action/",
            {"action_key": "APPROVE_VOUCHER"},
            format="json",
        )
        self.assertEqual(stale_res.status_code, 409)

    def test_02_deduplication_and_per_user_read_all_isolation(self):
        # Emit identical dedup_key twice -> only 1 notification per recipient
        for _ in range(2):
            DomainEventService.publish(
                event_type="report.generated",
                title="Trial Balance Ready",
                message="Trial Balance generated successfully.",
                company=self.company,
                actor=self.approver,
                category="REPORTS",
                module="REPORTS",
                popup_kind="SUCCESS",
                recipient_ids=[self.approver.id, self.maker.id],
                dedup_key="tb:gen:1",
                defer_until_commit=False,
            )

        self.assertEqual(Notification.objects.filter(company=self.company, recipient=self.approver, dedup_key="tb:gen:1").count(), 1)
        self.assertEqual(Notification.objects.filter(company=self.company, recipient=self.maker, dedup_key="tb:gen:1").count(), 1)

        # Maker runs read-all -> marks ONLY Maker read; Approver stays unread
        c_maker = self._client(self.maker)
        c_app = self._client(self.approver)
        self.assertEqual(c_maker.post("/api/notifications/read-all/").status_code, 200)
        self.assertEqual(c_maker.get("/api/notifications/unread-summary/").data["total_unread"], 0)
        self.assertGreaterEqual(c_app.get("/api/notifications/unread-summary/").data["total_unread"], 1)

    def test_03_chat_notification_integration_and_dm_privacy(self):
        c_maker = self._client(self.maker)
        c_app = self._client(self.approver)
        c_admin = self._client(self.admin)

        dm = c_maker.post("/api/chat/direct/", {"user_id": str(self.approver.id)}, format="json").data
        conv_id = dm["id"]
        c_maker.post(
            f"/api/chat/conversations/{conv_id}/messages/",
            {"body": "Private finance note: SECRET_DM_CHECK"},
            format="json",
        )

        # Approver receives chat notification; Admin (non-participant of DM) NEVER receives or sees it
        app_feed = c_app.get("/api/notifications/?tab=messages").data
        self.assertEqual(len(app_feed["results"]), 1)
        n_id = app_feed["results"][0]["id"]
        self.assertEqual(app_feed["results"][0]["metadata"]["conversation_id"], conv_id)

        admin_feed = c_admin.get("/api/notifications/?q=SECRET_DM_CHECK").data
        self.assertEqual(len(admin_feed["results"]), 0)
        self.assertEqual(c_admin.get(f"/api/notifications/{n_id}/").status_code, 404)

        # Executing OPEN_CHAT returns conversation_id and marks notification read
        open_res = c_app.post(f"/api/notifications/{n_id}/execute-action/", {"action_key": "OPEN_CHAT"}, format="json")
        self.assertEqual(open_res.status_code, 200)
        self.assertEqual(open_res.data["conversation_id"], conv_id)

    def test_04_critical_alert_overrides_dnd_and_quiet_hours_and_sanitizes_secrets(self):
        c_admin = self._client(self.admin)
        # Admin turns on DND and mutes general popup preferences
        c_admin.patch("/api/notifications/preferences/", {"category": "ALL", "dnd_enabled": True, "popup_enabled": False}, format="json")

        # Ordinary low-priority notification is marked SUPPRESSED_PREF
        DomainEventService.publish(
            event_type="system.info",
            title="Routine Info",
            message="Routine log cleanup note",
            company=self.company,
            category="SYSTEM",
            priority="LOW",
            recipient_ids=[self.admin.id],
            metadata={"api_key": "SUPERSECRET123"},
            defer_until_commit=False,
        )
        info_notif = Notification.objects.get(recipient=self.admin, event_type="system.info")
        self.assertEqual(info_notif.metadata.get("api_key"), "[REDACTED]")
        self.assertEqual(NotificationDelivery.objects.get(notification=info_notif).delivery_status, "SUPPRESSED_PREF")

        # Critical Security Alert cannot be suppressed by user DND!
        DomainEventService.publish(
            event_type="security.account_locked",
            title="Critical Security Breach Lockout",
            message="Multiple failed admin logins detected",
            company=self.company,
            category="SECURITY",
            priority="CRITICAL",
            popup_kind="CRITICAL",
            recipient_ids=[self.admin.id],
            is_mandatory_critical=True,
            defer_until_commit=False,
        )
        crit_notif = Notification.objects.get(recipient=self.admin, event_type="security.account_locked")
        self.assertEqual(NotificationDelivery.objects.get(notification=crit_notif).delivery_status, "DELIVERED")

    def test_05_confirmation_phrase_audit_search_archive_and_export(self):
        c_admin = self._client(self.admin)

        # Mismatched phrase rejected (403) and logged as DENIED
        bad = c_admin.post(
            "/api/notifications/confirm-audit/",
            {
                "action_type": "RESTORE_DATABASE",
                "source_reference": "BKP-100",
                "confirmation_phrase_used": "WRONG",
                "required_phrase": "RESTORE LIVE DB",
            },
            format="json",
        )
        self.assertEqual(bad.status_code, 403)
        self.assertTrue(ConfirmationAudit.objects.filter(action_type="RESTORE_DATABASE", authorization_result="DENIED").exists())

        # Exact phrase allowed
        ok = c_admin.post(
            "/api/notifications/confirm-audit/",
            {
                "action_type": "RESTORE_DATABASE",
                "source_reference": "BKP-100",
                "confirmation_phrase_used": "RESTORE LIVE DB",
                "required_phrase": "RESTORE LIVE DB",
            },
            format="json",
        )
        self.assertEqual(ok.status_code, 201)

        # Archive, restore & authorized export
        DomainEventService.publish(
            event_type="backup.completed",
            title="Full Backup Complete",
            message="Verified cleanly",
            company=self.company,
            category="BACKUP",
            recipient_ids=[self.admin.id],
            defer_until_commit=False,
        )
        nid = Notification.objects.filter(recipient=self.admin).first().id
        self.assertEqual(c_admin.post(f"/api/notifications/{nid}/archive/").status_code, 200)
        self.assertEqual(len(c_admin.get("/api/notifications/?archived=true").data["results"]), 1)
        self.assertEqual(c_admin.post(f"/api/notifications/{nid}/restore/").status_code, 200)

        csv_res = c_admin.get("/api/notifications/export/?file_format=csv")
        self.assertEqual(csv_res.status_code, 200)
        self.assertIn(b"Full Backup Complete", csv_res.content)

    def test_06_websocket_live_push_and_session_revocation_disconnect(self):
        async def _run():
            # Unauthenticated rejected
            anon = WsHarness(NotificationWebsocketConsumer.as_asgi(), "/ws/notifications/")
            anon.scope["user"] = None
            ok_anon, _ = await anon.connect()
            self.assertFalse(ok_anon)

            # Authenticated user connects
            comm = WsHarness(NotificationWebsocketConsumer.as_asgi(), "/ws/notifications/")
            comm.scope["user"] = self.approver
            ok, _ = await comm.connect()
            self.assertTrue(ok)
            hello = await comm.receive_json_from()
            self.assertEqual(hello["type"], "connected")

            # Publish notification -> arrives live on socket
            from channels.db import database_sync_to_async

            await database_sync_to_async(DomainEventService.publish)(
                event_type="software.updated",
                title="Update Installed",
                message="Maya OS v2.5.1 applied cleanly.",
                company=self.company,
                category="SYSTEM",
                popup_kind="SUCCESS",
                recipient_ids=[self.approver.id],
                defer_until_commit=False,
            )
            pushed = await comm.receive_json_from()
            self.assertEqual(pushed["type"], "notification_created")
            self.assertEqual(pushed["notification"]["title"], "Update Installed")

            # Logout / session revoke forces WebSocket disconnect cleanly
            await database_sync_to_async(broadcast_notification_force_disconnect)(self.approver.id, "Session revoked")
            rev = await comm.receive_json_from()
            self.assertEqual(rev["type"], "session_revoked")
            close_frame = await comm.receive_output(2)
            self.assertEqual(close_frame["type"], "websocket.close")
            self.assertEqual(close_frame["code"], 4401)
            await comm.wait(2)

        async_to_sync(_run)()

