from django.urls import path, include
from django.conf import settings
from .views import auth
from apps.accounts.views import VerifyEmailView
from .views.onboarding import GoogleLoginView, CompleteProfileView
from .views.purchase import PurchaseAPIView, PurchasePrecheckAPIView, CompletePartPaymentAPIView
from .views.distributor_lookup import get_user_distributor_ids
from .views.payment_validate import PaymentValidateAPIView
from .views.qr_config import ActiveQRConfigView
from apps.payments.views import CreateOrderView, VerifyPaymentView
from .views.kyc import UserKYCView
from .views.earnings import EarningsSummaryAPIView
from .views.dashboard import UserDashboardSummaryView
from .views.referral import UserReferralOverviewView
from .views.notifications import MarkAllNotificationsReadView, MarkNotificationReadView, UserDeviceTokenView, UserNotificationsView
from apps.business.products.urls import web_router as product_web_router
from apps.business.distributor.urls import web_router as distributor_web_router, web_urlpatterns as distributor_web_urlpatterns
from api.v1.web.platform_settings import PlatformSettingsView
from .views.sponsor_income import SponsorIncomeLedgerView, SponsorIncomeSummaryView
from .views.rank_progress import RankProgressView
from .views.user_rewards import UserRewardsView
from .views import binary_analysis as binary_analysis_views
from .views.binary_node_detail import BinaryNodeDetailView
from .views.chat import ConversationListView, ConversationMessageView, ConversationReadView
from .views.feature_flags import FeatureFlagsView
from .views.support import (
    UserSupportTicketCloseView,
    UserSupportTicketDetailView,
    UserSupportTicketListCreateView,
    UserSupportTicketMetricsView,
    UserSupportTicketReplyView,
)
from apps.business.wallet.views import MonthlyConversionRunView, SuperCoinBalanceView, SuperCoinLedgerListView, SuperCoinUseView, AllWalletsView, ProductPaymentConfigView
from apps.business.withdrawals.views import WithdrawalRequestCreateView
from apps.geo.views import MandalListView
from apps.business.invoice.views import (
    InvoicePublicSettingsView,
    UserShippingAddressListCreateView,
    UserShippingAddressDetailView,
    UserSetDefaultShippingAddressView,
    AdminCompanyProfileView,
    AdminDispatchAddressListCreateView,
    AdminDispatchAddressDetailView,
    AdminPlaceOfSupplyListCreateView,
    AdminPlaceOfSupplyDetailView,
    AdminInvoiceTermListCreateView,
    AdminInvoiceTermDetailView,
)
from apps.platform.settings.views import BranchViewSet
from rest_framework.routers import DefaultRouter as _BranchRouter
from apps.company.views import CompanyMemberViewSet as _CompanyMemberViewSet
from rest_framework.routers import DefaultRouter as _CompanyRouter
from rest_framework_simplejwt.views import TokenRefreshView

_branch_router = _BranchRouter()
_branch_router.register(r'branches', BranchViewSet, basename='public-branches')

_company_router = _CompanyRouter()
_company_router.register(r'company-members', _CompanyMemberViewSet, basename='public-company-members')

urlpatterns = [
    path('auth/login', auth.LoginView.as_view(), name='web-auth-login'),
    path('auth/login/', auth.LoginView.as_view(), name='web-auth-login-slash'),
    path('auth/register', auth.RegisterView.as_view(), name='web-auth-register'),
    path('auth/google-login', GoogleLoginView.as_view(), name='web-auth-google-login'),
    path('auth/complete-profile', CompleteProfileView.as_view(), name='web-auth-complete-profile'),
    path('auth/verify-email', VerifyEmailView.as_view(), name='web-auth-verify-email'),
    path('auth/refresh', TokenRefreshView.as_view(), name='web-auth-refresh'),
    path('auth/refresh/', TokenRefreshView.as_view(), name='web-auth-refresh-slash'),
    path('auth/profile', auth.ProfileView.as_view(), name='web-auth-profile'),
    path('auth/occupations', auth.OccupationListView.as_view(), name='web-auth-occupations'),
    path('auth/pincode-lookup', auth.PincodeLookupView.as_view(), name='web-auth-pincode-lookup'),
    path('auth/request-pin-otp', auth.RequestPinOTPView.as_view(), name='web-auth-request-pin-otp'),
    path('auth/verify-pin-otp', auth.VerifyPinOTPView.as_view(), name='web-auth-verify-pin-otp'),
    path('auth/reset-pin', auth.ResetPinView.as_view(), name='web-auth-reset-pin'),
    path('auth/set-login-pin', auth.SetLoginPinView.as_view(), name='web-auth-set-login-pin'),
    path('', include(product_web_router.urls)),
    path('', include(distributor_web_router.urls)),
    path('', include((distributor_web_urlpatterns, 'distributor-web'))),
    path('', include('apps.business.orders.urls')),
    path('wallet/', include('apps.business.wallet.urls')),
    path('withdrawals/', include('apps.business.withdrawals.urls')),
    path('pool/', include('apps.business.pool.urls')),
    path('rewards/', include('apps.business.rewards.urls')),
    path('lucky-dip/', include('apps.business.lucky_dip.urls')),
    path('purchase/', PurchaseAPIView.as_view(), name='web-purchase'),
    path('purchase/precheck/', PurchasePrecheckAPIView.as_view(), name='web-purchase-precheck'),
    path('purchase/<uuid:order_id>/complete-part-payment/', CompletePartPaymentAPIView.as_view(), name='web-purchase-complete-part-payment'),
    path('distributor-ids/', get_user_distributor_ids, name='web-distributor-ids'),
    path('payment-validate/', PaymentValidateAPIView.as_view(), name='web-payment-validate'),
    path('payments/create-order/', CreateOrderView.as_view(), name='web-payments-create-order'),
    path('payments/verify/', VerifyPaymentView.as_view(), name='web-payments-verify'),
    path('qr-config/active/', ActiveQRConfigView.as_view(), name='web-qr-config-active'),
    path('earnings/summary/', EarningsSummaryAPIView.as_view(), name='web-earnings-summary'),
    path('dashboard/summary/', UserDashboardSummaryView.as_view(), name='web-dashboard-summary'),
    path('referral/overview/', UserReferralOverviewView.as_view(), name='web-referral-overview'),
    path('kyc/', UserKYCView.as_view(), name='web-kyc'),
    path('platform-settings/', PlatformSettingsView.as_view(), name='web-platform-settings'),
    path('notifications/', UserNotificationsView.as_view(), name='web-notifications'),
    path('notifications/<uuid:notification_id>/read/', MarkNotificationReadView.as_view(), name='web-notification-read'),
    path('notifications/read-all/', MarkAllNotificationsReadView.as_view(), name='web-notifications-read-all'),
    path('notifications/devices/', UserDeviceTokenView.as_view(), name='web-notification-devices'),
    path('power-stream/', include('apps.business.power_stream.urls')),
    path('sponsor-income/summary/', SponsorIncomeSummaryView.as_view(), name='web-sponsor-income-summary'),
    path('sponsor-income/ledger/', SponsorIncomeLedgerView.as_view(), name='web-sponsor-income-ledger'),
    path('rank/progress/', RankProgressView.as_view(), name='web-rank-progress'),
    # ── Binary tree endpoints ─────────────────────────────────────────────────
    path('binary-analysis/', binary_analysis_views.BinaryAnalysisSummaryView.as_view(), name='web-binary-analysis'),
    path('binary-analysis/<uuid:distributor_id>/', binary_analysis_views.BinaryAnalysisDetailView.as_view(), name='web-binary-analysis-detail'),
    path('binary-tree/<uuid:distributor_id>/', binary_analysis_views.BinaryTreeStructureView.as_view(), name='web-binary-tree'),
    path('binary-progress/', binary_analysis_views.BinaryProgressView.as_view(), name='web-binary-progress'),
    path('binary-node/<uuid:distributor_id>/', BinaryNodeDetailView.as_view(), name='web-binary-node-detail'),
    # ── Feature flags ─────────────────────────────────────────────────────────
    path('feature-flags/', FeatureFlagsView.as_view(), name='web-feature-flags'),
    # ── Network chat ─────────────────────────────────────────────────────────
    path('chat/conversations/', ConversationListView.as_view(), name='web-chat-conversations'),
    path('chat/conversations/<uuid:conv_id>/messages/', ConversationMessageView.as_view(), name='web-chat-messages'),
    path('chat/conversations/<uuid:conv_id>/read/', ConversationReadView.as_view(), name='web-chat-read'),
    path('rewards/user-rewards/', UserRewardsView.as_view(), name='web-user-rewards'),
    path('supercoins/balance/', SuperCoinBalanceView.as_view(), name='web-supercoins-balance'),
    path('supercoins/ledger/', SuperCoinLedgerListView.as_view(), name='web-supercoins-ledger'),
    path('supercoins/use/', SuperCoinUseView.as_view(), name='web-supercoins-use'),
    path('conversion/run-monthly/', MonthlyConversionRunView.as_view(), name='web-conversion-run-monthly'),
    path('wallet/all-balances/', AllWalletsView.as_view(), name='web-wallet-all-balances'),
    path('products/<uuid:pk>/payment-config/', ProductPaymentConfigView.as_view(), name='web-product-payment-config'),
    path('withdrawal/request/', WithdrawalRequestCreateView.as_view(), name='web-withdrawal-request-alias'),
    path('support/tickets/', UserSupportTicketListCreateView.as_view(), name='web-support-tickets-list-create'),
    path('support/tickets/metrics/', UserSupportTicketMetricsView.as_view(), name='web-support-tickets-metrics'),
    path('support/tickets/<uuid:ticket_id>/', UserSupportTicketDetailView.as_view(), name='web-support-ticket-detail'),
    path('support/tickets/<uuid:ticket_id>/reply/', UserSupportTicketReplyView.as_view(), name='web-support-ticket-reply'),
    path('support/tickets/<uuid:ticket_id>/close/', UserSupportTicketCloseView.as_view(), name='web-support-ticket-close'),
    path('leads/', include('apps.leads.urls')),
    path('geo/mandals/', MandalListView.as_view(), name='web-geo-mandals'),
    # Invoice & address endpoints
    path('invoice/settings/', InvoicePublicSettingsView.as_view(), name='web-invoice-settings'),
    path('addresses/shipping/', UserShippingAddressListCreateView.as_view(), name='web-shipping-address-list'),
    path('addresses/shipping/<uuid:pk>/', UserShippingAddressDetailView.as_view(), name='web-shipping-address-detail'),
    path('addresses/shipping/<uuid:pk>/set-default/', UserSetDefaultShippingAddressView.as_view(), name='web-shipping-address-set-default'),
    # Admin invoice management
    path('admin/invoice/company/', AdminCompanyProfileView.as_view(), name='admin-invoice-company'),
    path('admin/invoice/dispatch-addresses/', AdminDispatchAddressListCreateView.as_view(), name='admin-dispatch-address-list'),
    path('admin/invoice/dispatch-addresses/<uuid:pk>/', AdminDispatchAddressDetailView.as_view(), name='admin-dispatch-address-detail'),
    path('admin/invoice/places-of-supply/', AdminPlaceOfSupplyListCreateView.as_view(), name='admin-places-of-supply-list'),
    path('admin/invoice/places-of-supply/<uuid:pk>/', AdminPlaceOfSupplyDetailView.as_view(), name='admin-places-of-supply-detail'),
    path('admin/invoice/terms/', AdminInvoiceTermListCreateView.as_view(), name='admin-invoice-terms-list'),
    path('admin/invoice/terms/<uuid:pk>/', AdminInvoiceTermDetailView.as_view(), name='admin-invoice-terms-detail'),
    # Public branches
    path('', include(_branch_router.urls)),
    # Public company members (management team + 48 director club)
    path('', include(_company_router.urls)),
    # Marketplace (product browsing, cart, wishlist, reviews)
    path('marketplace/', include('api.v1.web.marketplace_urls')),
    path('telemetry/', include('apps.telemetry.urls')),
]

# Expose a test endpoint for local Sentry testing only when DEBUG is enabled
if getattr(settings, 'DEBUG', False):
    urlpatterns += [
        path('test-error/', auth.TestErrorView.as_view(), name='web-test-error'),
    ]
