"""
Pydantic schemas for Google Workspace model JSONFields.

These schemas validate the JSONFields on Google Workspace models:
- GoogleWorkspaceSyncLog: groups_found, roles_before, roles_after,
  changes_made, metadata

Usage:
    from lightwave.schema.pydantic.models.google import (
        SyncRolesSchema,
        SyncChangeSchema,
        SyncMetadataSchema,
    )
"""

from typing import Any

from pydantic import Field

from lightwave.schema.pydantic.core.base import JSONFieldSchema


class SyncRolesSchema(JSONFieldSchema):
    """
    Schema for GoogleWorkspaceSyncLog.roles_before and roles_after JSONFields.

    Maps tenant IDs to role assignments.

    Example:
        {
            "cineos": "tenant_admin",
            "createos": "member",
            "lightwave_ltd": "platform_admin"
        }
    """

    # Dynamic keys (tenant schema names) mapped to role strings
    # Using extra="allow" from JSONFieldSchema base


class SyncChangeSchema(JSONFieldSchema):
    """
    Schema for individual change in GoogleWorkspaceSyncLog.changes_made list.

    Records a single role change during sync.

    Example:
        {
            "tenant": "cineos",
            "action": "grant",
            "role": "tenant_admin",
            "reason": "Member of platform-admins@lightwave-media.ltd"
        }
    """

    tenant: str = Field(..., description="Tenant schema name")
    action: str = Field(..., description="Action taken (grant, revoke, upgrade, downgrade)")
    role: str = Field(..., description="Role that was changed")
    previous_role: str | None = Field(None, description="Previous role if changed")
    reason: str = Field("", description="Reason for the change")
    group_email: str | None = Field(None, description="Group that triggered this change")


class SyncMetadataSchema(JSONFieldSchema):
    """
    Schema for GoogleWorkspaceSyncLog.metadata JSONField.

    Additional metadata about the sync operation.

    Example:
        {
            "oauth_provider": "google",
            "api_version": "v1",
            "groups_api_calls": 3,
            "admin_api_calls": 1,
            "cache_hits": 5,
            "dry_run": false,
            "triggered_by": "oauth_login"
        }
    """

    oauth_provider: str = Field("google", description="OAuth provider used")
    api_version: str | None = Field(None, description="Google API version")
    groups_api_calls: int = Field(0, ge=0, description="Number of Groups API calls")
    admin_api_calls: int = Field(0, ge=0, description="Number of Admin API calls")
    cache_hits: int = Field(0, ge=0, description="Number of cache hits")
    dry_run: bool = Field(False, description="Whether this was a dry run")
    triggered_by: str | None = Field(None, description="What triggered the sync")
    error_details: dict[str, Any] | None = Field(None, description="Error details if failed")
    warnings: list[str] = Field(default_factory=list, description="Non-fatal warnings")


def validate_groups_list(groups: list[str] | None) -> list[str]:
    """
    Validate a list of Google Workspace group emails.

    Used for GoogleWorkspaceSyncLog.groups_found field.

    Args:
        groups: List of group email addresses

    Returns:
        Validated group list (lowercased, stripped)
    """
    if not groups:
        return []
    return [g.lower().strip() for g in groups if isinstance(g, str) and g.strip()]
