from fastapi import Request, Query, Depends, Header, APIRouter, HTTPException
from fastapi.responses import JSONResponse
import pytz
import os
from datetime import datetime, timedelta
from connectors.firebase.firebase import Firebase
import utility.function as func
from connectors.bigquery.bq import BigQuery
import time

import logging
logging.basicConfig(level=logging.INFO)
timezone_utc = pytz.utc
timezone_bkk = pytz.timezone('Asia/Bangkok')

fb = Firebase(host=os.environ.get("FIREBASE_HOST"))

router = APIRouter()

LOGGING_PREFIX = "api_job_profile"

@router.post("", description="Scheduled job to update profile data to BigQuery")
async def post_api_job_profile_update(default_request: Request):
    try:
        account = fb.db.reference().child("account").get(shallow=True)
        for acc in account:
            # check acc process
            userInRange = []
            accActive = []
            allProfile = fb.db.reference().child(f"account/{acc}/profile").get(shallow=True)
            for id in allProfile:
                proUpdate = fb.db.reference().child(f"account/{acc}/profile/{id}/updated_at").get()
                updated_at = datetime.fromisoformat(proUpdate)
                now = datetime.now(updated_at.tzinfo)
                if now.replace(minute=0, second=0, microsecond=0) - timedelta(hours=1) <= datetime.fromisoformat(proUpdate) <= now.replace(minute=0, second=0, microsecond=0):
                    pro = fb.db.reference().child(f"account/{acc}/profile/{id}").get()
                    userInRange.append(pro)

            if userInRange:
                bq = BigQuery()
                bq.delete_data(project_name='customer-360-profile', dataset_name='client_' + acc, table_name='customer_profile_temp')
                
                loadData = []
                for user in userInRange:
                    transformed_data = func.Function.transformProfiletoBQ(user)
                    loadData.append(transformed_data)

                error = bq.load_data(target_table=f"client_{acc}.customer_profile_temp", data=loadData)
                if error:
                    logging.error(f"Error loading data to BigQuery: {error}")
                else:
                    logging.info(f"Data loaded to BigQuery for eventId")

                time.sleep(10)
                # Process update when match
                condition = "ON (ori.user_pseudo_id = temp.user_pseudo_id) "
                bq.delete_when_match(project_name='customer-360-profile', dataset_name_ori='client_' + acc, table_name_ori='customer_profile', dataset_name_temp='client_' + acc, table_name_temp='customer_profile_temp', condition=condition)
                bq.load_data(target_table=f"client_{acc}.customer_profile", data=loadData)
        return JSONResponse(status_code=200, content={'status': 'success', 'message': 'Profile data processed successfully'})
    except Exception as e:
        logging.error(f"Error parsing {LOGGING_PREFIX}_{default_request.path_params}: {e}")
        return JSONResponse(status_code=500, content={'status': 'error', 'message': str(e)})