"""SaaS Multi-Tenancy & Tenant Context Service.

Provides tenant resolution, permission guards, and subscription plan quota enforcement.
"""

from functools import wraps
from datetime import datetime, timezone
from flask import g, session, request, abort, redirect, url_for, flash
from flask_login import current_user

from app.extensions import db
from app.models.organization import Organization
from app.models.subscription_plan import SubscriptionPlan
from app.models.user import User


def get_current_tenant() -> Organization:
    """
    Resolves the active organization (tenant) for the current request.
    Resolution priority:
    1. Already cached in Flask's request context `g.tenant`
    2. SuperAdmin impersonation context from session ('impersonate_org_id')
    3. Logged-in user's assigned organization
    4. Fallback to default primary organization (ID 1 or first active)
    """
    if hasattr(g, 'tenant') and g.tenant is not None:
        return g.tenant

    tenant = None

    # 1. Check SuperAdmin impersonation session
    impersonate_id = session.get('active_tenant_id')
    if impersonate_id:
        tenant = db.session.get(Organization, impersonate_id)

    # 2. Check current authenticated user's organization
    if not tenant and current_user.is_authenticated:
        if current_user.organization:
            tenant = current_user.organization
        elif current_user.organization_id:
            tenant = db.session.get(Organization, current_user.organization_id)

    # 3. Fallback to primary default organization
    if not tenant:
        tenant = Organization.query.filter_by(status='active').order_by(Organization.id.asc()).first()
        if not tenant:
            tenant = Organization.query.order_by(Organization.id.asc()).first()

    g.tenant = tenant
    return tenant


def is_superadmin_user(user) -> bool:
    """Helper to check if a user possesses master SaaS platform superadmin authority."""
    if not user or not getattr(user, 'is_authenticated', False):
        return False
    return bool(getattr(user, 'is_superadmin', False) or getattr(user, 'email', '') == 'admin@ngo.org')


def superadmin_required(f):
    """
    Decorator to restrict access strictly to Platform Super Administrators.
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated:
            return redirect(url_for('auth.login', next=request.url))
        if not is_superadmin_user(current_user):
            flash('Access denied: Platform Super Admin privileges required.', 'error')
            abort(403)
        return f(*args, **kwargs)
    return decorated_function


def check_staff_quota(organization: Organization):
    """
    Checks if the tenant organization is within its staff account limit.
    Returns: (is_allowed: bool, current_count: int, max_limit: int, message: str)
    """
    if not organization or not organization.plan:
        return True, 0, -1, "OK"

    max_staff = organization.plan.max_staff
    if max_staff == -1:
        return True, 0, -1, "Unlimited staff allowed on this plan."

    current_staff_count = User.query.filter_by(
        organization_id=organization.id
    ).join(User.role).filter(User.role.has(role_name='Admin') | User.role.has(role_name='Verifier') | User.role.has(role_name='Finance')).count()

    if current_staff_count >= max_staff:
        return False, current_staff_count, max_staff, f"Plan staff limit reached ({current_staff_count}/{max_staff}). Please upgrade your plan."
    
    return True, current_staff_count, max_staff, "OK"


def check_campaign_quota(organization: Organization):
    """
    Checks if the organization can create another campaign according to plan limits.
    """
    if not organization or not organization.plan:
        return True, 0, -1, "OK"

    max_campaigns = organization.plan.max_campaigns
    if max_campaigns == -1:
        return True, 0, -1, "Unlimited campaigns allowed."

    from app.models.campaign import Campaign
    active_count = Campaign.query.count() # In tenant-isolated setup, filter by org
    if active_count >= max_campaigns:
        return False, active_count, max_campaigns, f"Plan campaign limit reached ({active_count}/{max_campaigns}). Upgrade for more."

    return True, active_count, max_campaigns, "OK"


def get_tenant_metrics(organization: Organization):
    """
    Aggregates usage statistics for the NGO Admin Billing & Subscription dashboard.
    """
    if not organization:
        return {}

    plan = organization.plan or SubscriptionPlan.query.filter_by(slug='starter').first()
    
    # Calculate staff count
    staff_count = User.query.filter_by(organization_id=organization.id).count()
    
    # Calculate donations this month
    from app.models.donation import Donation
    now = datetime.now(timezone.utc)
    start_of_month = datetime(now.year, now.month, 1, tzinfo=timezone.utc)
    
    donations_this_month = Donation.query.filter(
        Donation.donated_at >= start_of_month
    ).count()

    total_donations_collected = db.session.query(
        db.func.sum(Donation.amount)
    ).filter(Donation.status.in_(['matched', 'success', 'received'])).scalar() or 0.0

    # Quotas
    staff_limit = plan.max_staff if plan else 5
    donation_limit = plan.max_donations_month if plan else 500
    campaign_limit = plan.max_campaigns if plan else 3

    staff_pct = 100 if staff_limit == -1 else min(int((staff_count / max(staff_limit, 1)) * 100), 100)
    donation_pct = 100 if donation_limit == -1 else min(int((donations_this_month / max(donation_limit, 1)) * 100), 100)

    return {
        'organization': organization,
        'plan': plan,
        'staff_count': staff_count,
        'staff_limit': staff_limit,
        'staff_pct': staff_pct,
        'donations_this_month': donations_this_month,
        'donation_limit': donation_limit,
        'donation_pct': donation_pct,
        'campaign_limit': campaign_limit,
        'total_donations_collected': total_donations_collected,
        'is_trial': organization.is_trial,
        'trial_ends_at': organization.trial_ends_at,
    }
