from __future__ import annotations

import re

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.employee import Employee
from app.models.tenant import Tenant, TenantMembership

DEFAULT_TENANT_ID = "default"
PLATFORM_TENANT_ID = "platform"
_TENANT_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$")


def required_tenant_id(value: object) -> str:
    tenant_id = str(value or "").strip()
    if not _TENANT_PATTERN.fullmatch(tenant_id):
        raise ValueError("tenant_id 缺失或格式不合法。")
    return tenant_id


class TenantRegistryService:
    def __init__(self, db: Session) -> None:
        self.db = db

    def ensure_builtin(self) -> None:
        builtins = (
            (DEFAULT_TENANT_ID, DEFAULT_TENANT_ID, "默认企业"),
            (PLATFORM_TENANT_ID, PLATFORM_TENANT_ID, "平台管理域"),
        )
        for tenant_id, tenant_code, name in builtins:
            if self.db.get(Tenant, tenant_id) is None:
                self.db.add(
                    Tenant(
                        tenant_id=tenant_id,
                        tenant_code=tenant_code,
                        name=name,
                        status="active",
                    )
                )
        self.db.flush()

    def require_active(self, tenant_id: object) -> Tenant:
        normalized = required_tenant_id(tenant_id)
        tenant = self.db.scalar(
            select(Tenant).where(
                Tenant.tenant_id == normalized,
                Tenant.status == "active",
            )
        )
        if tenant is None:
            raise LookupError("租户不存在或当前不可用。")
        return tenant

    def active_tenant_ids(self, *, include_platform: bool = False) -> tuple[str, ...]:
        statement = select(Tenant.tenant_id).where(Tenant.status == "active")
        if not include_platform:
            statement = statement.where(Tenant.tenant_id != PLATFORM_TENANT_ID)
        return tuple(self.db.scalars(statement.order_by(Tenant.tenant_id)).all())

    def ensure_employee_membership(self, employee: Employee) -> TenantMembership:
        tenant_id = required_tenant_id(employee.tenant_id)
        self.require_active(tenant_id)
        membership = self.db.scalar(
            select(TenantMembership).where(
                TenantMembership.tenant_id == tenant_id,
                TenantMembership.employee_id == employee.id,
            )
        )
        if membership is None:
            membership = TenantMembership(
                tenant_id=tenant_id,
                employee_id=employee.id,
                status="active",
                is_primary=True,
            )
            self.db.add(membership)
        elif membership.status != "active":
            membership.status = "active"
        self.db.flush()
        return membership
