from fastapi import Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from src.marketing.apps.post import schema
from src.marketing.apps.post.service import (
    create_calendar_post,
    get_calendar_posts_by_calendar_id_and_date_range,
    get_post_types_by_post_id,
    partial_update_calendar_post,
    get_calendar_post_by_id,
    update_calendar_post,
    delete_calendar_post,
    create_calendar_post_type,
    # get_all_calendar_post_types,
    get_calendar_post_type_by_id,
    update_calendar_post_type,
    delete_calendar_post_type,
    generate_text_content,
    generate_image_content,
    get_url_info


)
from src.utils.db import get_db





def create_calendar_post_controller(post_data: schema.CalendarPostCreate, db: Session):
    try:
        return create_calendar_post(db, post_data)
    except HTTPException as e:
        raise e  
    except Exception as e:
        print("Create calendar post error:", str(e))  
        raise HTTPException(status_code=500, detail="Internal Server Error")





# Get a calendar post by ID
def get_calendar_post_by_id_controller(
    post_id: int,
    db: Session
) -> schema.CalendarPostOut:
    try:
        return get_calendar_post_by_id(db, post_id)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))


# Get Data  calendar post by branch_id and schedule_date
# def get_calendar_posts_by_calendar_id_and_date_range_controller(
#     calendar_id: int,
#     start_date: str,
#     end_date: str,
#     db: Session = Depends(get_db)
# ) -> List[schema.CalendarPostOut]:
#     try:
#         result =  get_calendar_posts_by_calendar_id_and_date_range(db, calendar_id, start_date, end_date)
#         if not result:
#             raise HTTPException(
#                 status_code=status.HTTP_404_NOT_FOUND,
#                 detail={
#                     "success": False,
#                     "message": "No calendar posts found for the given date range",
#                     "data": []
#                 }
#             )
           
#         return result

#     except Exception as e:
#         raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
def get_calendar_posts_by_calendar_id_and_date_range_controller(
    calendar_id: int,
    start_date: str,
    end_date: str,
    db: Session
) -> List[schema.CalendarPostOut]:
    try:
        result = get_calendar_posts_by_calendar_id_and_date_range(db, calendar_id, start_date, end_date)

        if not result:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail={
                    "success": False,
                    "message": "No calendar posts found for the given date range",
                    "data": []
                }
            )
        return result

    except HTTPException as e:
        # Re-raise without wrapping
        raise e

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "success": False,
                "message": str(e),
                "data": []
            }
        )

# Update a calendar post
def update_calendar_post_controller(
    post_id: int,
    post_data: schema.CalendarPostUpdate,
    db: Session
) -> schema.CalendarPostOut:
    try:
        return update_calendar_post(db, post_id, post_data)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

#partial_update_controller
def partial_update_calendar_post_controller(post_id: int, post_data: schema.CalendarPostUpdate, db: Session) -> schema.CalendarPostOut:
    try:
        return partial_update_calendar_post(post_id, post_data, db)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))


# Delete a calendar post
def delete_calendar_post_controller(
    post_id: int,
    db: Session
) -> None:
    try:
        delete_calendar_post(db, post_id)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

#--------------------------------------------------|
# Calendar Post Type Services   
#--------------------------------------------------|

# Create a calendar post type controller
def create_calendar_post_type_controller(
    post_type_data: schema.CalendarPostTypeCreate,
    db: Session
) -> schema.CalendarPostTypeOut:
    try:
        return create_calendar_post_type(post_type_data, db)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))


# Get a calendar post type by ID controller
def get_calendar_post_type_by_id_controller(
    post_type_id: int,
    db: Session
) -> schema.CalendarPostTypeOut:
    try:
        result =  get_calendar_post_type_by_id(db, post_type_id)
        if not result:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail={
                    "success": False,
                    "message": "Calendar post type not found",
                    "data": None
                }
            )
        return result
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
    

# Get post types by post_id (query param)
def get_calendar_post_types_by_post_id_controller(post_id: int, db: Session):
    try:
        result =  get_post_types_by_post_id(db, post_id)
        if not result:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail={
                    "success": False,
                    "message": "No post types found for the given post ID",
                    "data": []
                }
            )
        return result
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    

# Update a calendar post type controller
def update_calendar_post_type_controller(
    post_type_id: int,
    post_type_data: schema.CalendarPostTypeUpdate,
    db: Session
) -> schema.CalendarPostTypeOut:
    try:
        return update_calendar_post_type(db, post_type_id, post_type_data)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))


# Delete a calendar post type controller
def delete_calendar_post_type_controller(
    post_type_id: int,
    db: Session
) -> None:
    try:
        delete_calendar_post_type(post_type_id,db)
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
    

# ---------------------------------------------------------|
# Generate Content Controller
# ---------------------------------------------------------|

#Generate Text controller
def generate_text_controller(request_data: schema.GenerateTextContent):
    try:
        # Validate required fields
        if not request_data.post_type:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "success": False,
                    "message": "post_type is required",
                    "data": None
                }
            )
        
        if not request_data.input_text or not request_data.input_text.strip():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "success": False,
                    "message": "input_text is required and cannot be empty",
                    "data": None
                }
            )
        
        return generate_text_content(request_data)
    
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, 
            detail=str(e)
        )
    


#Generate Image controller
def generate_image_controller(request_data: schema.GenerateImageContent, db: Session):
    try:
        if not request_data.post_type:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "success": False,
                    "message": "post_type is required",
                    "data": None
                }
            )
        
        if not request_data.input_text or not request_data.input_text.strip():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "success": False,
                    "message": "input_text is required for image generation",
                    "data": None
                }
            )
        
    
        return generate_image_content(request_data, db)

    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


#---------------------------------------------------|
#    Get URL information controller
#---------------------------------------------------|

def check_url(url_data: schema.URLInfoRequest) -> schema.URLInfoResponse:
    try:
        result =  get_url_info(url_data.url)
        if not result:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "success": False,
                    "message": "input_url is required and cannot be empty",
                    "data": None
                }
            )
        return result
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))



from .service import delete_upload_photo
##---------------------------------------
#DELETE PHOTO CONTROLLER
#----------------------------------
def delete_uplod_photo_controller(db:Session,image_id:int,post_type_id:int):
    delete_photo_service = delete_upload_photo(db=db,image_id=image_id,post_type_id=post_type_id)
    if not delete_photo_service:
          raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
                detail={
                    "success": False,
                    "message": "Image not Found",
                    "data": None
                }
            )
    return {"success": True, 
            "message": "Image deleted successfully"}
            
        



