"""Architecture tests — Beauty Business module boundary enforcement."""
from __future__ import annotations

import ast
from pathlib import Path

from app.models import appointments as appt_models
from app.models import catalog as catalog_models
from app.models import customers as customer_models
from app.models import foundation as models
from app.models import marketing as marketing_models
from app.models import packages as package_models
from app.models import salon as salon_models
from app.models import staff as staff_models

FORBIDDEN_IMPORT_PREFIXES = (
    "backend.services.accounting",
    "backend.services.crm",
    "backend.services.loyalty",
    "backend.services.communication",
    "backend.services.sports_center",
    "backend.services.automation",
    "backend.services.notification",
    "backend.services.file_storage",
    "backend.services.identity_access",
    "backend.core_service",
)

FOUNDATION_MODELS = [
    models.BeautyOrganization,
    models.BeautyBranch,
    models.BeautyRole,
    models.BeautyPermission,
    models.ExternalProviderConfig,
    models.BookingEngineRegistration,
    models.BeautyConfiguration,
    models.BeautySetting,
    models.BeautyAuditLog,
]

BOOKING_MODELS = [
    appt_models.StaffSchedule,
    appt_models.StaffAvailability,
    appt_models.ScheduleException,
    appt_models.AppointmentType,
    appt_models.Appointment,
    appt_models.AppointmentStatusHistory,
    appt_models.WaitingListEntry,
]

SALON_MODELS = [
    salon_models.TreatmentRoom,
    salon_models.Station,
    salon_models.BranchOperatingHours,
    salon_models.BranchPolicy,
]

CATALOG_MODELS = [
    catalog_models.ServiceCategory,
    catalog_models.BeautyService,
    catalog_models.ServiceVariant,
    catalog_models.BranchServiceAssignment,
    catalog_models.ServiceMediaRef,
]

CUSTOMER_MODELS = [
    customer_models.CustomerProfile,
    customer_models.CustomerPreference,
    customer_models.VisitHistoryEntry,
    customer_models.CustomerDocumentRef,
]

PACKAGE_MODELS = [
    package_models.PackageDefinition,
    package_models.PackageLine,
    package_models.CustomerPackage,
    package_models.PackageRedemption,
    package_models.MembershipPlan,
    package_models.CustomerMembership,
    package_models.MembershipLifecycleEvent,
]

STAFF_MODELS = [
    staff_models.StaffProfile,
    staff_models.StaffSkill,
    staff_models.StaffCertificate,
    staff_models.CommissionRule,
    staff_models.CommissionEntry,
]

MARKETING_MODELS = [
    marketing_models.MarketingCampaignRef,
    marketing_models.LoyaltyIntegrationConfig,
    marketing_models.CommunicationIntegrationConfig,
    marketing_models.IntegrationDispatch,
]


def test_all_models_have_tenant_id():
    from app.core.database import Base
    import app.models  # noqa: F401

    skip = {"alembic_version"}
    for table in Base.metadata.tables.values():
        if table.name in skip:
            continue
        assert "tenant_id" in table.columns, f"{table.name} missing tenant_id"


def test_foundation_aggregates_are_independent():
    assert len(FOUNDATION_MODELS) == 9
    for model in FOUNDATION_MODELS:
        assert hasattr(model, "tenant_id")
        assert hasattr(model, "id")
        assert not model.__mapper__.relationships


def test_booking_aggregates_are_independent():
    assert len(BOOKING_MODELS) == 7
    for model in BOOKING_MODELS:
        assert hasattr(model, "tenant_id")
        assert not model.__mapper__.relationships


def test_no_driver_or_dispatch_tables():
    from app.core.database import Base
    import app.models  # noqa: F401

    names = set(Base.metadata.tables.keys())
    assert "appointments" in names
    assert "outbox_events" in names
    forbidden = {"drivers", "dispatch_jobs", "routes", "fleets", "vehicles"}
    assert forbidden.isdisjoint(names)


def test_permissions_defined():
    from app.permissions.definitions import ALL_PERMISSIONS, PERMISSION_PREFIXES

    assert "beauty_business.view" in ALL_PERMISSIONS
    assert "beauty_business.organizations.create" in ALL_PERMISSIONS
    assert "beauty_business.appointments.create" in ALL_PERMISSIONS
    assert "beauty_business.appointments.confirm" in ALL_PERMISSIONS
    assert "beauty_business.services.manage" in ALL_PERMISSIONS or "beauty_business.services.create" in ALL_PERMISSIONS
    assert "beauty_business.marketing.create" in ALL_PERMISSIONS
    assert "beauty_business.integrations.create" in ALL_PERMISSIONS
    for prefix in PERMISSION_PREFIXES:
        assert any(p.startswith(prefix.rstrip(".")) or p.startswith(prefix) for p in ALL_PERMISSIONS)


def test_events_defined():
    from app.events.types import BeautyBusinessEventType

    assert BeautyBusinessEventType.ORGANIZATION_CREATED.value == "beauty_business.organization.created"
    assert BeautyBusinessEventType.BRANCH_CREATED.value == "beauty_business.branch.created"
    assert (
        BeautyBusinessEventType.EXTERNAL_PROVIDER_REGISTERED.value
        == "beauty_business.external_provider.registered"
    )
    assert (
        BeautyBusinessEventType.BOOKING_ENGINE_REGISTERED.value
        == "beauty_business.booking_engine.registered"
    )
    assert BeautyBusinessEventType.APPOINTMENT_CREATED.value == "beauty_business.appointment.created"
    assert BeautyBusinessEventType.APPOINTMENT_CONFIRMED.value == "beauty_business.appointment.confirmed"
    assert BeautyBusinessEventType.APPOINTMENT_STATUS_CHANGED.value == "beauty_business.appointment.status_changed"


def test_platform_provider_contracts_exist():
    from app.providers import (
        AIProvider,
        AccountingProvider,
        BookingEngineProvider,
        CRMProvider,
        CommunicationProvider,
        DeliveryProvider,
        ExperienceProvider,
        IdentityProvider,
        LoyaltyProvider,
        NotificationProvider,
        StorageProvider,
    )

    assert AccountingProvider is not None
    assert CommunicationProvider is not None
    assert BookingEngineProvider is not None
    assert ExperienceProvider is not None
    assert LoyaltyProvider is not None
    assert CRMProvider is not None
    assert NotificationProvider is not None
    assert StorageProvider is not None
    assert AIProvider is not None
    assert IdentityProvider is not None
    assert DeliveryProvider is not None


def test_no_forbidden_service_imports():
    root = Path(__file__).resolve().parents[1]
    violations: list[str] = []
    for path in root.rglob("*.py"):
        if "tests" in path.parts:
            continue
        tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
        for node in ast.walk(tree):
            if isinstance(node, ast.Import):
                for alias in node.names:
                    for forbidden in FORBIDDEN_IMPORT_PREFIXES:
                        if alias.name.startswith(forbidden) or forbidden in alias.name:
                            violations.append(f"{path}: import {alias.name}")
            elif isinstance(node, ast.ImportFrom) and node.module:
                for forbidden in FORBIDDEN_IMPORT_PREFIXES:
                    if node.module.startswith(forbidden) or forbidden in node.module:
                        violations.append(f"{path}: from {node.module}")
    assert violations == []


def test_api_ownership_is_beauty_business_only():
    from app.api.v1 import api_router

    prefixes = {getattr(r, "path", "") for r in api_router.routes}
    joined = " ".join(sorted(prefixes))
    assert "/organizations" in joined or any("/organizations" in p for p in prefixes)
    assert "/branches" in joined or any("/branches" in p for p in prefixes)
    assert "/appointments" in joined or any("/appointments" in p for p in prefixes)
    forbidden = ("/accounting/", "/crm/", "/notification/", "/automation/", "/sports-center/")
    for name in forbidden:
        assert name not in joined


def test_folder_structure():
    root = Path(__file__).resolve().parents[2]
    required = [
        "app/models",
        "app/repositories",
        "app/services",
        "app/validators",
        "app/schemas",
        "app/events",
        "app/permissions",
        "app/providers",
        "app/policies",
        "app/specifications",
        "app/commands",
        "app/queries",
        "app/api/v1",
        "app/tests",
        "alembic/versions",
        "README.md",
    ]
    for rel in required:
        assert (root / rel).exists(), f"missing {rel}"
