from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import json
from datetime import datetime
from ...shared.config.database import get_db
from ...shared.config.logging_config import get_logger
from ..models.page_content import PageContent, PageType
from ...security.services.privacy_admin_service import privacy_admin_service
from ..schemas.privacy import CookieConsent, CookieConsentResponse, UpdateCookieConsentRequest, CookieCategoryPreferences
from ..schemas.admin_privacy import PublicPrivacyConfigResponse
logger = get_logger(__name__)
router = APIRouter(prefix='/privacy', tags=['privacy'])

def serialize_page_content(content: PageContent) -> dict:
    return {
        'id': content.id,
        'page_type': content.page_type.value,
        'title': content.title,
        'subtitle': content.subtitle,
        'description': content.description,
        'content': content.content,
        'meta_title': content.meta_title,
        'meta_description': content.meta_description,
        'meta_keywords': content.meta_keywords,
        'og_title': content.og_title,
        'og_description': content.og_description,
        'og_image': content.og_image,
        'canonical_url': content.canonical_url,
        'is_active': content.is_active,
        'created_at': content.created_at.isoformat() if content.created_at else None,
        'updated_at': content.updated_at.isoformat() if content.updated_at else None
    }

@router.get('/')
async def get_privacy_content(db: Session=Depends(get_db)):
    try:
        content = db.query(PageContent).filter(PageContent.page_type == PageType.PRIVACY).first()
        if not content:
            return {'status': 'success', 'data': {'page_content': None, 'is_active': False}}
        if not content.is_active:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Privacy policy page is currently disabled')
        content_dict = serialize_page_content(content)
        return {'status': 'success', 'data': {'page_content': content_dict}}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f'Error fetching privacy content: {str(e)}', exc_info=True)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching privacy content: {str(e)}')

@router.get('/cookie-consent', response_model=CookieConsentResponse)
async def get_cookie_consent(db: Session=Depends(get_db)):
    """
    Get the default cookie consent structure.
    Note: Actual consent is stored client-side (localStorage), this endpoint provides the default structure.
    """
    try:
        # Return default consent structure
        # The actual consent state is managed client-side
        consent = CookieConsent(
            version=1,
            updated_at=datetime.utcnow(),
            has_decided=False,
            categories=CookieCategoryPreferences(
                necessary=True,  # Always true
                analytics=False,
                marketing=False,
                preferences=False
            )
        )
        return CookieConsentResponse(status='success', data=consent)
    except Exception as e:
        logger.error(f'Error fetching cookie consent: {str(e)}', exc_info=True)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching cookie consent: {str(e)}')

@router.post('/cookie-consent', response_model=CookieConsentResponse)
async def update_cookie_consent(payload: UpdateCookieConsentRequest, db: Session=Depends(get_db)):
    """
    Update cookie consent preferences.
    Note: This endpoint acknowledges the consent update. Actual consent is stored client-side.
    """
    try:
        # Create updated consent structure
        consent = CookieConsent(
            version=1,
            updated_at=datetime.utcnow(),
            has_decided=True,
            categories=CookieCategoryPreferences(
                necessary=True,  # Always true
                analytics=payload.analytics if payload.analytics is not None else False,
                marketing=payload.marketing if payload.marketing is not None else False,
                preferences=payload.preferences if payload.preferences is not None else False
            )
        )
        return CookieConsentResponse(status='success', data=consent)
    except Exception as e:
        logger.error(f'Error updating cookie consent: {str(e)}', exc_info=True)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error updating cookie consent: {str(e)}')

@router.get('/config', response_model=PublicPrivacyConfigResponse)
async def get_public_privacy_config(db: Session=Depends(get_db)):
    """
    Get public privacy configuration including cookie policy settings and integration configs.
    This endpoint is public and does not require authentication.
    """
    try:
        config = privacy_admin_service.get_public_privacy_config(db)
        return PublicPrivacyConfigResponse(status='success', data=config)
    except Exception as e:
        logger.error(f'Error fetching public privacy config: {str(e)}', exc_info=True)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching public privacy config: {str(e)}')
