from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from prometheus_client import Counter, generate_latest, CONTENT_TYPE_LATEST
from starlette.responses import Response
from typing import List
from app.api import auth, tenants, customers, templates, notifications, analytics, tracking, notification_settings, ab_testing, customer_management, feedback, automation, billing, balance, payment_gateways, integrations, oauth_crm, industry_templates, crm_webhooks, custom_triggers, telegram, telegram_webhooks, telegram_mtproto, telegram_settings, bitrix_byo, api_keys, webhooks, email_configs, custom_fields, vk_groups

app = FastAPI(title="Notification Service", version="0.1.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Публичные эндпоинты (не требуют авторизации)
@app.get("/api/v1/app/domain")
def get_app_domain():
    """Получить домен приложения для webhook URL"""
    from app.core.config import get_settings
    settings = get_settings()
    return {"domain": settings.APP_DOMAIN}

@app.get("/api/v1/integrations/providers")
def get_crm_providers():
    """Получить список доступных CRM-провайдеров - публичный эндпоинт"""
    providers = [
        {
            "id": "bitrix24",
            "name": "Bitrix24",
            "description": "Bitrix24 подключается в один клик через единое приложение",
            "connection_type": "oauth",
            "setup_time": "1 минута",
            "logo_url": "/logos/bitrix24.png"
        },
        {
            "id": "amocrm",
            "name": "amoCRM",
            "description": "amoCRM - простая интеграция через API",
            "connection_type": "oauth",
            "setup_time": "2 минуты",
            "logo_url": "/logos/amocrm.png"
        },
        {
            "id": "1c",
            "name": "1С",
            "description": "1С облачная или локальная версия",
            "connection_type": "api_key",
            "setup_time": "5 минут",
            "logo_url": "/logos/1c.png"
        },
        {
            "id": "custom",
            "name": "Другая система",
            "description": "Подключите любую CRM через вебхуки",
            "connection_type": "webhook",
            "setup_time": "3 минуты",
            "logo_url": "/logos/custom.png"
        }
    ]
    
    return providers

# Include routers
app.include_router(auth.router, prefix="/api/v1")
app.include_router(tenants.router, prefix="/api/v1")
app.include_router(customers.router, prefix="/api/v1")
app.include_router(templates.router, prefix="/api/v1")
app.include_router(notifications.router, prefix="/api/v1")
app.include_router(analytics.router, prefix="/api/v1")
app.include_router(tracking.router, prefix="/api/v1")
app.include_router(notification_settings.router, prefix="/api/v1")
app.include_router(ab_testing.router, prefix="/api/v1")
app.include_router(customer_management.router, prefix="/api/v1")
app.include_router(feedback.router, prefix="/api/v1/feedback", tags=["feedback"])
app.include_router(automation.router, prefix="/api/v1", tags=["automation"])
app.include_router(billing.router, prefix="/api/v1/billing", tags=["billing"])
app.include_router(balance.router, prefix="/api/v1/balance", tags=["balance"])
app.include_router(payment_gateways.router, prefix="/api/v1/payment", tags=["payment"])
app.include_router(integrations.router, prefix="/api/v1", tags=["integrations"])
app.include_router(oauth_crm.router, prefix="/api/v1", tags=["oauth"])
app.include_router(industry_templates.router, prefix="/api/v1", tags=["industry-templates"])
app.include_router(crm_webhooks.router, prefix="/api/v1", tags=["crm-webhooks"])
app.include_router(custom_triggers.router, prefix="/api/v1", tags=["custom-triggers"])
app.include_router(telegram.router, prefix="/api/v1/telegram", tags=["telegram"])
app.include_router(telegram_webhooks.router, prefix="/tg", tags=["telegram-webhooks"])
app.include_router(telegram_mtproto.router, prefix="/api/v1/telegram", tags=["telegram-mtproto"])
app.include_router(telegram_settings.router, prefix="/api/v1", tags=["telegram-settings"])
app.include_router(bitrix_byo.router, prefix="/api/v1", tags=["bitrix-byo"])
app.include_router(api_keys.router, prefix="/api/v1", tags=["api-keys"])
app.include_router(webhooks.router, prefix="/api/v1", tags=["webhooks"])
app.include_router(email_configs.router, prefix="/api/v1", tags=["email-configs"])
app.include_router(custom_fields.router, prefix="/api/v1", tags=["custom-fields"])
app.include_router(vk_groups.router, prefix="/api/v1", tags=["vk-groups"])

sent_counter = Counter(
    "notifications_sent_total",
    "Total sent notifications",
    ["tenant", "channel"],
)
failed_counter = Counter(
    "notifications_failed_total",
    "Total failed notifications",
    ["tenant", "channel"],
)


@app.get("/healthz")
def healthz() -> dict:
    return {"status": "ok"}


@app.get("/metrics")
def metrics() -> Response:
    return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)


@app.get("/")
def root() -> dict:
    return {"service": "notification", "version": app.version}

