from fastapi import APIRouter, status, Request
from utils.auth_dependency import handles_authentication, user_dependency
from utils.database import db_dependency
from utils.exceptions import AuthenticationError
from schemas.retell import (RetellWebhookResponse)
from repositories import agent_repository
import httpx
import os
from retell import Retell
from schemas.phone_number import PhoneNumberCreate, PhoneNumberResponse
from typing import List
from models import SampleAgent, Company ,Users, PhoneNumber, Company , Agent, WeeklySchedule
import json
from repositories.user_repository import UserRepository
from utils.constants import BusinessType, RegisterStep
from datetime import datetime, timedelta, timezone
import pytz
from fastapi.responses import JSONResponse

router = APIRouter(prefix="/api/retell", tags=["Retell"])

RETELL_API_KEY = os.getenv("RETELL_API_KEY")


@router.post("/inbound-webhook", status_code=status.HTTP_200_OK)
async def inbound_webhook(request: Request, db: db_dependency):
    body = await request.json()
    print("📞 Incoming Retell webhook:", body)

    call_inbound = body.get("call_inbound", {})
    to_number = call_inbound.get("to_number")

    if not to_number:
        return JSONResponse(content={}, status_code=200)

    # 1️⃣ Look up the phone entry in DB
    phone_entry = db.query(PhoneNumber).filter(
        PhoneNumber.phone_number == to_number
    ).first()

    if not phone_entry:
        # No matching phone → disconnect call
        return JSONResponse(content={}, status_code=200)

    # 2️⃣ Get Agent & Company
    agent_entry = db.query(Agent).filter(
        Agent.id == phone_entry.agent_id
    ).first()

    company_entry = db.query(Company).filter(
        Company.id == agent_entry.company_id
    ).first()

    # 3️⃣ Fetch schedules for company
    weekly_schedules = (
        db.query(WeeklySchedule)
        .filter(WeeklySchedule.company_id == company_entry.id)
        .all()
    )

    # 4️⃣ Compute current time with timezone
    timezone = pytz.timezone("Asia/Karachi")  # adjust if needed
    now = datetime.now(timezone)
    current_day = now.weekday()  # Monday=0, Sunday=6 in Python
    db_day = (current_day + 1) % 7  # shift so Sunday=0 ... Saturday=6

    current_time = now.time()  # datetime.time object
    timezone_offset = now.utcoffset().total_seconds() / 3600

    # 5️⃣ Find today's schedule
    today_schedule = next((s for s in weekly_schedules if s.day_of_week == db_day), None)

    is_off_hours = True
    if today_schedule:
        if not today_schedule.is_day_off:
            if today_schedule.start_time <= current_time <= today_schedule.end_time:
                is_off_hours = False

    # # Debug log
    # print(f"🕒 Day={db_day}, Now={current_time}, Start={today_schedule.start_time if today_schedule else None}, "
    #       f"End={today_schedule.end_time if today_schedule else None}, OffHours={is_off_hours}")

    # 6️⃣ Prepare response
    response_body = {
        "call_inbound": {
            "dynamic_variables": {
                "is_off_hours": str(is_off_hours).lower(),  # "true" / "false"
                "current_time": now.strftime("%H:%M"),
                "timezone_offset": str(timezone_offset)
            },
            "metadata": {
                "bot_switch_reason": "off_hours" if is_off_hours else "business_hours"
            }
        }
    }

    return JSONResponse(content=response_body, status_code=200)