#!/usr/bin/env python3
"""Seed the non-billable Stripe-preview trial for the AbsoluteMS tenant."""

from __future__ import annotations

import json
import sys
from datetime import datetime, timedelta
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(BASE_DIR))
loaded_platform = sys.modules.get("platform")
if loaded_platform is not None and not hasattr(loaded_platform, "__path__"):
    del sys.modules["platform"]

from sqlalchemy import select
from config.control_plane import get_control_plane_session
from bridge_platform.tenants.models import (
    App,
    Plan,
    Tenant,
    TenantApp,
    TenantLimit,
    TenantSubscription,
)


APP_CATALOG = {
    "wp_invoices": {
        "name": "WP Invoices",
        "route": "/api/v1/wp_invoices",
        "description": "Digitise and analyse invoices with AI.",
        "category": "AI & Finance",
    },
    "abn_lookup_app": {
        "name": "ABN Lookup",
        "route": "/api/v1/abn_lookup_app",
        "description": "Look up Australian business registration data.",
        "category": "Business Data",
    },
    "leave_form_app": {
        "name": "Leave Forms",
        "route": "/api/v1/leave_form_app",
        "description": "Manage leave requests and related workflows.",
        "category": "Workforce",
    },
    "aroflo_connector_app": {
        "name": "AroFlo Connector",
        "route": "/api/v1/aroflo_connector_app",
        "description": "Connect authorised workflows to AroFlo.",
        "category": "Integrations",
    },
    "wp_invoices_mail_app": {
        "name": "Invoice Mail Intake",
        "route": "/api/v1/wp_invoices_mail_app",
        "description": "Process invoice messages through a managed mailbox.",
        "category": "AI & Finance",
    },
    "voiceordering_app": {
        "name": "Voice Ordering",
        "route": "/api/v1/voiceordering_app",
        "description": "Capture product orders using voice workflows.",
        "category": "Ordering",
    },
    "messaging_service": {
        "name": "Messaging Service",
        "route": "/api/v1/messaging_service",
        "description": "Deliver controlled SMS and email templates through tenant providers.",
        "category": "Platform Services",
    },
    "qr_service": {
        "name": "QR Service",
        "route": "/api/v1/qr_service",
        "description": "Create and resolve generic revocable QR contexts.",
        "category": "Platform Services",
    },
}

ENABLED_APPS = {
    "wp_invoices",
    "abn_lookup_app",
    "leave_form_app",
    "aroflo_connector_app",
    "messaging_service",
    "qr_service",
}
DEFAULT_LIMITS = {
    "storage_mb": (1024, None, "block"),
    "ai_tokens_monthly": (100000, None, "block"),
    "requests_per_minute": (120, 60, "block"),
}


def main() -> int:
    now = datetime.utcnow()
    with get_control_plane_session() as session:
        tenant = session.get(Tenant, "absolutems")
        if tenant is None:
            raise RuntimeError("Tenant absolutems does not exist")

        plan = session.get(Plan, "dev")
        if plan is None:
            plan = Plan(
                plan_id="dev",
                code="dev",
                name="Development",
                price_monthly=0,
                currency="AUD",
                description="Development subscription used for platform integration testing.",
            )
            session.add(plan)
        tenant.plan_id = "dev"

        for app_id, definition in APP_CATALOG.items():
            app = session.get(App, app_id)
            if app is None:
                app = App(
                    app_id=app_id,
                    display_name=definition["name"],
                    module_path=f"apps.{app_id}",
                    route_prefix=definition["route"],
                    is_active=True,
                )
                session.add(app)
            app.display_name = definition["name"]
            app.route_prefix = definition["route"]
            app.is_active = True
            app.metadata_json = {
                "description": definition["description"],
                "category": definition["category"],
            }

        subscription = session.execute(
            select(TenantSubscription)
            .where(TenantSubscription.tenant_id == tenant.tenant_id)
            .limit(1)
        ).scalar_one_or_none()
        if subscription is None:
            subscription = TenantSubscription(
                subscription_id="absolutems-dev",
                tenant_id=tenant.tenant_id,
                plan_id="dev",
            )
            session.add(subscription)
        subscription.plan_id = "dev"
        subscription.provider = "stripe"
        subscription.provider_customer_id = None
        subscription.provider_subscription_id = None
        subscription.status = "trialing"
        subscription.current_period_start = now
        subscription.current_period_end = now + timedelta(days=30)
        subscription.cancel_at_period_end = False
        subscription.metadata_json = {
            "purpose": "phase_2_stripe_integration_trial",
            "billing_state": "pending_prices",
            "billable": False,
        }

        for app_id in ENABLED_APPS:
            binding = session.execute(
                select(TenantApp)
                .where(TenantApp.tenant_id == tenant.tenant_id, TenantApp.app_id == app_id)
                .limit(1)
            ).scalar_one_or_none()
            if binding is None:
                binding = TenantApp(tenant_id=tenant.tenant_id, app_id=app_id)
                session.add(binding)
            binding.is_enabled = True
            binding.config_json = {"enabled": True}

        for name, (value, window, policy) in DEFAULT_LIMITS.items():
            limit = session.execute(
                select(TenantLimit)
                .where(
                    TenantLimit.tenant_id == tenant.tenant_id,
                    TenantLimit.app_id.is_(None),
                    TenantLimit.limit_name == name,
                )
                .limit(1)
            ).scalar_one_or_none()
            if limit is None:
                limit = TenantLimit(
                    tenant_id=tenant.tenant_id,
                    app_id=None,
                    limit_name=name,
                )
                session.add(limit)
            limit.limit_value = value
            limit.window_seconds = window
            limit.overage_policy = policy
            limit.metadata_json = {"source": "development_seed"}

        session.commit()

    print(
        json.dumps(
            {
                "status": "ok",
                "tenant": "absolutems",
                "subscription": "trialing",
                "provider": "stripe",
                "billable": False,
                "enabled_apps": sorted(ENABLED_APPS),
                "limits": {name: value[0] for name, value in DEFAULT_LIMITS.items()},
            },
            indent=2,
        )
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
