from datetime import datetime, timezone

from sqlalchemy import Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.db.database import Base


def _now() -> str:
    return datetime.now(timezone.utc).isoformat()


class Tenant(Base):
    __tablename__ = "tenants"

    id: Mapped[str] = mapped_column(String, primary_key=True)  # slug, e.g. "aarogya-hospital"
    name: Mapped[str] = mapped_column(String)
    vertical: Mapped[str] = mapped_column(String)  # hospital | real_estate | tourism
    bot_name: Mapped[str] = mapped_column(String)
    welcome_message: Mapped[str] = mapped_column(Text)
    primary_color: Mapped[str] = mapped_column(String, default="#1f4bd8")
    position: Mapped[str] = mapped_column(String, default="right")
    quick_actions: Mapped[str] = mapped_column(Text, default="[]")  # JSON list[str]
    allowed_origin: Mapped[str | None] = mapped_column(String, nullable=True)

    faqs: Mapped[list["Faq"]] = relationship(back_populates="tenant", cascade="all, delete-orphan")


class Faq(Base):
    __tablename__ = "faqs"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    category: Mapped[str] = mapped_column(String)
    question: Mapped[str] = mapped_column(Text)
    answer: Mapped[str] = mapped_column(Text)
    status: Mapped[str] = mapped_column(String, default="published")  # published | draft
    updated_at: Mapped[str] = mapped_column(String, default=_now)

    tenant: Mapped["Tenant"] = relationship(back_populates="faqs")


class Lead(Base):
    """A callback request captured when the bot can't (or shouldn't) fully resolve
    something itself — e.g. Real Estate's "Talk to an Agent". Generic across
    verticals; `agent_id`/`property_id` are only meaningful where they exist."""

    __tablename__ = "leads"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    name: Mapped[str] = mapped_column(String)
    phone: Mapped[str] = mapped_column(String)
    email: Mapped[str | None] = mapped_column(String, nullable=True)
    message: Mapped[str | None] = mapped_column(Text, nullable=True)
    property_id: Mapped[str | None] = mapped_column(ForeignKey("properties.id"), nullable=True)
    agent_id: Mapped[str | None] = mapped_column(ForeignKey("agents.id"), nullable=True)
    status: Mapped[str] = mapped_column(String, default="new")  # new | contacted | closed
    created_at: Mapped[str] = mapped_column(String, default=_now)


# ── Hospital vertical ───────────────────────────────────────────────────

class Department(Base):
    __tablename__ = "departments"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    name: Mapped[str] = mapped_column(String)
    description: Mapped[str] = mapped_column(Text)


class Doctor(Base):
    __tablename__ = "doctors"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    name: Mapped[str] = mapped_column(String)
    specialization: Mapped[str] = mapped_column(String)
    department_id: Mapped[str] = mapped_column(ForeignKey("departments.id"))
    department_name: Mapped[str] = mapped_column(String)
    qualification: Mapped[str] = mapped_column(String)
    experience_years: Mapped[int] = mapped_column(Integer)
    languages: Mapped[str] = mapped_column(String)  # comma separated
    branch: Mapped[str] = mapped_column(String)
    consultation_fee: Mapped[int] = mapped_column(Integer)
    rating: Mapped[float] = mapped_column(Float)
    status: Mapped[str] = mapped_column(String, default="active")  # active | unavailable
    next_available: Mapped[str] = mapped_column(String)
    bio: Mapped[str] = mapped_column(Text, default="")
    reviews: Mapped[int] = mapped_column(Integer, default=0)
    # JSON-encoded weekly schedule: [{day, enabled, slotDuration, sessions: [{start, end}]}, ...]
    schedule_json: Mapped[str] = mapped_column(Text, default="[]")


class Appointment(Base):
    __tablename__ = "appointments"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    doctor_id: Mapped[str] = mapped_column(ForeignKey("doctors.id"))
    patient_name: Mapped[str] = mapped_column(String)
    patient_phone: Mapped[str] = mapped_column(String)
    patient_email: Mapped[str] = mapped_column(String)
    date: Mapped[str] = mapped_column(String)  # ISO date, e.g. '2026-08-14'
    time: Mapped[str] = mapped_column(String)  # e.g. '09:30 AM'
    status: Mapped[str] = mapped_column(String, default="confirmed")  # confirmed | cancelled
    created_at: Mapped[str] = mapped_column(String, default=_now)


# ── Real estate vertical ────────────────────────────────────────────────

class Agent(Base):
    __tablename__ = "agents"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    name: Mapped[str] = mapped_column(String)
    phone: Mapped[str] = mapped_column(String)
    email: Mapped[str] = mapped_column(String)


class Property(Base):
    __tablename__ = "properties"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    title: Mapped[str] = mapped_column(String)
    type: Mapped[str] = mapped_column(String)  # apartment | villa | plot | commercial
    bhk: Mapped[int | None] = mapped_column(Integer, nullable=True)
    city: Mapped[str] = mapped_column(String)
    locality: Mapped[str] = mapped_column(String)
    price: Mapped[int] = mapped_column(Integer)  # INR
    area_sqft: Mapped[int] = mapped_column(Integer)
    amenities: Mapped[str] = mapped_column(String)  # comma separated
    status: Mapped[str] = mapped_column(String, default="available")  # available | sold | rented
    agent_id: Mapped[str] = mapped_column(ForeignKey("agents.id"))
    description: Mapped[str] = mapped_column(Text)


class SiteVisit(Base):
    __tablename__ = "site_visits"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    property_id: Mapped[str] = mapped_column(ForeignKey("properties.id"))
    visitor_name: Mapped[str] = mapped_column(String)
    visitor_phone: Mapped[str] = mapped_column(String)
    visitor_email: Mapped[str] = mapped_column(String)
    date: Mapped[str] = mapped_column(String)  # ISO date
    time: Mapped[str] = mapped_column(String)  # e.g. '11:30 AM'
    status: Mapped[str] = mapped_column(String, default="confirmed")  # confirmed | cancelled
    created_at: Mapped[str] = mapped_column(String, default=_now)


# ── Tourism vertical ────────────────────────────────────────────────────

class Destination(Base):
    __tablename__ = "destinations"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    name: Mapped[str] = mapped_column(String)
    region: Mapped[str] = mapped_column(String)
    best_time_to_visit: Mapped[str] = mapped_column(String)
    description: Mapped[str] = mapped_column(Text)


class Package(Base):
    __tablename__ = "packages"

    id: Mapped[str] = mapped_column(String, primary_key=True)
    tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"))
    title: Mapped[str] = mapped_column(String)
    destination_id: Mapped[str] = mapped_column(ForeignKey("destinations.id"))
    destination_name: Mapped[str] = mapped_column(String)
    duration_days: Mapped[int] = mapped_column(Integer)
    price: Mapped[int] = mapped_column(Integer)  # INR per person
    category: Mapped[str] = mapped_column(String)  # honeymoon | family | adventure | pilgrimage
    inclusions: Mapped[str] = mapped_column(Text)
    rating: Mapped[float] = mapped_column(Float)
