"""
Privacy and DSAR endpoints.

Handles data deletion requests for enrichment vault data.
"""

import logging
from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import delete, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from ...auth_core import require_org_context
from ...db import get_session
from ...model_defs.enrichment_vault import EnrichmentVault
from ...models import EnrichmentUsage

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/privacy", tags=["privacy"])

# Common email field names in SFDC
EMAIL_FIELDS = {"Email", "PersonEmail", "WorkEmail", "PersonalEmail"}


@router.delete("/enrichment/personal-data")
async def delete_personal_data(
    email: str = Query(..., description="Email address to redact from vault"),
    org=Depends(require_org_context),
    db: AsyncSession = Depends(get_session),
):
    """
    Delete personal data from enrichment vault (DSAR compliance).

    Removes all vault entries containing the specified email and marks
    related usage rows as redacted.

    This operation:
    1. Finds all vault entries with this email in value_after
    2. Deletes those vault entries
    3. Marks related EnrichmentUsage rows as redacted
    """
    if not email or "@" not in email:
        raise HTTPException(status_code=400, detail="Valid email address required")

    # Step 1: Find usage_ids containing this email value
    vault_q = (
        select(EnrichmentVault.usage_id)
        .where(
            EnrichmentVault.account_id == org.account_id,
            or_(
                EnrichmentVault.value_after == email,
                (EnrichmentVault.field_name.in_(EMAIL_FIELDS))
                & (EnrichmentVault.value_after == email),
            ),
        )
        .distinct()
    )
    result = await db.execute(vault_q)
    affected_usage_ids = result.scalars().all()

    # Step 2: Delete vault entries
    del_stmt = delete(EnrichmentVault).where(
        EnrichmentVault.account_id == org.account_id,
        or_(
            EnrichmentVault.value_after == email,
            (EnrichmentVault.field_name.in_(EMAIL_FIELDS))
            & (EnrichmentVault.value_after == email),
        ),
    )
    del_result = await db.execute(del_stmt)
    deleted_rows = del_result.rowcount or 0

    # Step 3: Mark ONLY affected usage rows as redacted
    if affected_usage_ids:
        upd = (
            update(EnrichmentUsage)
            .where(EnrichmentUsage.id.in_(affected_usage_ids))
            .values(redacted_at=datetime.utcnow(), redacted_reason=f"DSAR: {email}")
        )
        await db.execute(upd)

    await db.commit()

    # Optional: Emit audit event if telemetry is available
    try:
        # Attempt to log audit event (graceful failure if not available)
        from ...services.telemetry import audit_log

        await audit_log.create(
            account_id=org.account_id,
            user_email=getattr(org, "user_email", None),
            action="dsar_delete",
            entity_type="enrichment_vault",
            details={
                "email_redacted": email,
                "rows_deleted": int(deleted_rows),
                "usage_rows_redacted": len(affected_usage_ids),
            },
        )
    except (ImportError, AttributeError, Exception) as e:
        # Audit logging is optional - don't fail the request
        logger.debug(f"Could not log DSAR audit event: {e}")

    logger.info(
        f"DSAR: Deleted {deleted_rows} vault rows for email={email}, "
        f"redacted {len(affected_usage_ids)} usage rows (account={org.account_id})"
    )

    return {
        "deleted_rows": int(deleted_rows),
        "redacted_usage_ids": len(affected_usage_ids),
        "message": f"Successfully deleted {deleted_rows} enrichment records containing {email}",
    }
