from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import json
from ...shared.config.database import get_db
from ...shared.config.logging_config import get_logger
from ..models.page_content import PageContent, PageType
logger = get_logger(__name__)
router = APIRouter(prefix='/home', tags=['home'])

def serialize_page_content(content: PageContent) -> dict:
    def safe_json_loads(value, default=None):
        """Safely parse JSON string, return default if invalid or empty"""
        if not value:
            return default
        try:
            parsed = json.loads(value)
            return parsed if parsed else default
        except (json.JSONDecodeError, TypeError):
            return default
    
    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,
        'contact_info': safe_json_loads(content.contact_info, {}),
        'map_url': content.map_url,
        'social_links': safe_json_loads(content.social_links, {}),
        'footer_links': safe_json_loads(content.footer_links, {}),
        'badges': safe_json_loads(content.badges, []),
        'copyright_text': content.copyright_text,
        'hero_title': content.hero_title,
        'hero_subtitle': content.hero_subtitle,
        'hero_image': content.hero_image,
        'hero_video_url': content.hero_video_url,
        'hero_video_poster': content.hero_video_poster,
        'story_content': content.story_content,
        'values': safe_json_loads(content.values, []),
        'features': safe_json_loads(content.features, []),
        'features_section_title': content.features_section_title,
        'features_section_subtitle': content.features_section_subtitle,
        'about_hero_image': content.about_hero_image,
        'mission': content.mission,
        'vision': content.vision,
        'team': safe_json_loads(content.team, []),
        'timeline': safe_json_loads(content.timeline, []),
        'achievements': safe_json_loads(content.achievements, []),
        'amenities_section_title': content.amenities_section_title,
        'amenities_section_subtitle': content.amenities_section_subtitle,
        'amenities': safe_json_loads(content.amenities, []),
        'testimonials_section_title': content.testimonials_section_title,
        'testimonials_section_subtitle': content.testimonials_section_subtitle,
        'testimonials': safe_json_loads(content.testimonials, []),
        'gallery_section_title': content.gallery_section_title,
        'gallery_section_subtitle': content.gallery_section_subtitle,
        'gallery_images': safe_json_loads(content.gallery_images, []),
        'luxury_section_title': content.luxury_section_title,
        'luxury_section_subtitle': content.luxury_section_subtitle,
        'luxury_section_image': content.luxury_section_image,
        'luxury_features': safe_json_loads(content.luxury_features, []),
        'luxury_gallery_section_title': content.luxury_gallery_section_title,
        'luxury_gallery_section_subtitle': content.luxury_gallery_section_subtitle,
        'luxury_gallery': safe_json_loads(content.luxury_gallery, []),
        'luxury_testimonials_section_title': content.luxury_testimonials_section_title,
        'luxury_testimonials_section_subtitle': content.luxury_testimonials_section_subtitle,
        'luxury_testimonials': safe_json_loads(content.luxury_testimonials, []),
        'about_preview_title': content.about_preview_title,
        'about_preview_subtitle': content.about_preview_subtitle,
        'about_preview_content': content.about_preview_content,
        'about_preview_image': content.about_preview_image,
        'stats': safe_json_loads(content.stats, []),
        'stats_section_title': content.stats_section_title,
        'stats_section_subtitle': content.stats_section_subtitle,
        'rooms_section_title': content.rooms_section_title,
        'rooms_section_subtitle': content.rooms_section_subtitle,
        'rooms_section_button_text': content.rooms_section_button_text,
        'rooms_section_button_link': content.rooms_section_button_link,
        'rooms_section_enabled': content.rooms_section_enabled,
        'luxury_services_section_title': content.luxury_services_section_title,
        'luxury_services_section_subtitle': content.luxury_services_section_subtitle,
        'services_section_button_text': content.services_section_button_text,
        'services_section_button_link': content.services_section_button_link,
        'services_section_limit': content.services_section_limit,
        'luxury_services': safe_json_loads(content.luxury_services, []),
        'luxury_experiences_section_title': content.luxury_experiences_section_title,
        'luxury_experiences_section_subtitle': content.luxury_experiences_section_subtitle,
        'luxury_experiences': safe_json_loads(content.luxury_experiences, []),
        'awards_section_title': content.awards_section_title,
        'awards_section_subtitle': content.awards_section_subtitle,
        'awards': safe_json_loads(content.awards, []),
        'cta_title': content.cta_title,
        'cta_subtitle': content.cta_subtitle,
        'cta_button_text': content.cta_button_text,
        'cta_button_link': content.cta_button_link,
        'cta_image': content.cta_image,
        'partners_section_title': content.partners_section_title,
        'partners_section_subtitle': content.partners_section_subtitle,
        'partners': safe_json_loads(content.partners, []),
        'sections_enabled': safe_json_loads(content.sections_enabled, {}),
        'newsletter_section_title': content.newsletter_section_title,
        'newsletter_section_subtitle': content.newsletter_section_subtitle,
        'newsletter_placeholder': content.newsletter_placeholder,
        'newsletter_button_text': content.newsletter_button_text,
        'newsletter_enabled': content.newsletter_enabled,
        'trust_badges_section_title': content.trust_badges_section_title,
        'trust_badges_section_subtitle': content.trust_badges_section_subtitle,
        'trust_badges': safe_json_loads(content.trust_badges, []),
        'trust_badges_enabled': content.trust_badges_enabled,
        'promotions_section_title': content.promotions_section_title,
        'promotions_section_subtitle': content.promotions_section_subtitle,
        'promotions': safe_json_loads(content.promotions, []),
        'promotions_enabled': content.promotions_enabled,
        'blog_section_title': content.blog_section_title,
        'blog_section_subtitle': content.blog_section_subtitle,
        'blog_posts_limit': content.blog_posts_limit,
        'blog_enabled': content.blog_enabled,
        '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_home_content(db: Session=Depends(get_db)):
    try:
        content = db.query(PageContent).filter(PageContent.page_type == PageType.HOME).first()
        if not content:
            return {'status': 'success', 'data': {'page_content': None}}
        content_dict = serialize_page_content(content)
        return {'status': 'success', 'data': {'page_content': content_dict}}
    except Exception as e:
        logger.error(f'Error fetching home content: {str(e)}', exc_info=True)
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching home content: {str(e)}')