from __future__ import annotations

from datetime import date, datetime, timezone

from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column

from app.core.db.common import CommonBase


class Client(CommonBase):
    __tablename__ = "clients"
    __table_args__ = (
        UniqueConstraint("tenant_id", "client_code", name="uq_clients_tenant_code"),
        UniqueConstraint("tenant_id", "pan", name="uq_clients_tenant_pan"),
        UniqueConstraint("tenant_id", "gstin", name="uq_clients_tenant_gstin"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id"), nullable=False, index=True)
    branch_id: Mapped[int] = mapped_column(ForeignKey("branches.id"), nullable=False, index=True)
    partner_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
    client_group_id: Mapped[int | None] = mapped_column(ForeignKey("client_groups.id", ondelete="SET NULL"), nullable=True, index=True)
    group_relationship: Mapped[str | None] = mapped_column(String(100), nullable=True)
    is_group_head: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
    default_performing_partner_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
    default_review_partner_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
    referred_by_consultant_id: Mapped[int | None] = mapped_column(ForeignKey("consultant_profiles.id", ondelete="SET NULL"), nullable=True, index=True)
    referral_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    referral_reference: Mapped[str | None] = mapped_column(String(200), nullable=True)
    referral_status: Mapped[str] = mapped_column(String(30), nullable=False, default="active", index=True)
    communication_routing_mode: Mapped[str] = mapped_column(String(30), nullable=False, default="client_and_consultant", index=True)
    engagement_mode: Mapped[str] = mapped_column(String(30), nullable=False, default="internal_managed", index=True)
    client_code: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    client_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
    trade_name: Mapped[str | None] = mapped_column(String(200), nullable=True)
    client_type: Mapped[str] = mapped_column(String(100), nullable=False, default="Other")
    pan: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True)
    gstin: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True)
    tan: Mapped[str | None] = mapped_column(String(20), nullable=True)
    cin_llpin: Mapped[str | None] = mapped_column(String(30), nullable=True)
    msme_no: Mapped[str | None] = mapped_column(String(50), nullable=True)
    iec_code: Mapped[str | None] = mapped_column(String(30), nullable=True)
    contact_person_name: Mapped[str | None] = mapped_column(String(200), nullable=True)
    contact_person_designation: Mapped[str | None] = mapped_column(String(200), nullable=True)
    mobile: Mapped[str | None] = mapped_column(String(20), nullable=True)
    alternate_mobile: Mapped[str | None] = mapped_column(String(20), nullable=True)
    email: Mapped[str | None] = mapped_column(String(255), nullable=True)
    alternate_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
    address_line_1: Mapped[str | None] = mapped_column(String(255), nullable=True)
    address_line_2: Mapped[str | None] = mapped_column(String(255), nullable=True)
    city: Mapped[str | None] = mapped_column(String(100), nullable=True)
    state: Mapped[str | None] = mapped_column(String(100), nullable=True)
    pincode: Mapped[str | None] = mapped_column(String(20), nullable=True)
    country: Mapped[str | None] = mapped_column(String(100), nullable=True, default="India")
    status: Mapped[str] = mapped_column(String(20), nullable=False, default="active", index=True)
    client_category: Mapped[str | None] = mapped_column(String(100), nullable=True)
    risk_category: Mapped[str | None] = mapped_column(String(50), nullable=True)
    onboarding_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    closing_date: Mapped[date | None] = mapped_column(Date, nullable=True)

    # Client acceptance / continuance controls for AQMM and peer review evidence.
    acceptance_status: Mapped[str] = mapped_column(String(30), nullable=False, default="pending_review", index=True)
    acceptance_required: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    independence_check_completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    conflict_check_completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    kyc_completed: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    engagement_letter_required: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    engagement_letter_received: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    acceptance_approved_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
    acceptance_approved_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    acceptance_review_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    acceptance_rejection_reason: Mapped[str | None] = mapped_column(Text, nullable=True)

    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    gst_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    income_tax_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    tds_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    roc_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    audit_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    pf_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    esi_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    professional_tax_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    payroll_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    msme_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    import_export_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    is_archived: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    archived_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    updated_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    portal_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
    created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)


class ClientAuditLog(CommonBase):
    __tablename__ = "client_audit_logs"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    client_id: Mapped[int] = mapped_column(ForeignKey("clients.id"), nullable=False, index=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id"), nullable=False, index=True)
    branch_id: Mapped[int] = mapped_column(ForeignKey("branches.id"), nullable=False, index=True)
    actor_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    action: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    summary: Mapped[str] = mapped_column(String(255), nullable=False)
    payload_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)

class ClientAcceptanceDeclaration(CommonBase):
    """Digital independence/conflict declaration requested from partner, manager or staff.

    Each row is an auditable declaration.  The client level checkbox is derived
    only when all applicable declaration rows are answered without issue.
    """

    __tablename__ = "client_acceptance_declarations"
    __table_args__ = (
        UniqueConstraint("client_id", "declaration_type", "assigned_user_id", name="uq_client_acceptance_declaration_user"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
    branch_id: Mapped[int | None] = mapped_column(ForeignKey("branches.id", ondelete="SET NULL"), nullable=True, index=True)
    declaration_type: Mapped[str] = mapped_column(String(30), nullable=False, index=True)
    assigned_user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
    assigned_role_snapshot: Mapped[str | None] = mapped_column(String(120), nullable=True)
    declaration_text: Mapped[str] = mapped_column(Text, nullable=False)
    status: Mapped[str] = mapped_column(String(30), nullable=False, default="pending", index=True)
    response_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    issue_details: Mapped[str | None] = mapped_column(Text, nullable=True)
    responded_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    response_ip: Mapped[str | None] = mapped_column(String(80), nullable=True)
    response_user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True)
    requested_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    requested_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)


class ClientKycVerification(CommonBase):
    """KYC verification layer on top of existing permanent client documents.

    This does not duplicate client uploads.  It stores whether the existing
    permanent documents are enough and who verified them.
    """

    __tablename__ = "client_kyc_verifications"
    __table_args__ = (
        UniqueConstraint("client_id", name="uq_client_kyc_verification_client"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
    branch_id: Mapped[int | None] = mapped_column(ForeignKey("branches.id", ondelete="SET NULL"), nullable=True, index=True)
    status: Mapped[str] = mapped_column(String(30), nullable=False, default="pending_documents", index=True)
    required_document_summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    available_document_summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    verification_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    verified_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
    verified_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    rejected_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
    rejected_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)


class ClientEngagementLetter(CommonBase):
    """Client acceptance engagement letter with digital OTP or manual signed upload."""

    __tablename__ = "client_engagement_letters"
    __table_args__ = (
        UniqueConstraint("client_id", "letter_code", "version_no", name="uq_client_engagement_letter_code_version"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
    branch_id: Mapped[int | None] = mapped_column(ForeignKey("branches.id", ondelete="SET NULL"), nullable=True, index=True)
    letter_code: Mapped[str] = mapped_column(String(80), nullable=False, default="STANDARD", index=True)
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    body_text: Mapped[str] = mapped_column(Text, nullable=False)
    version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
    status: Mapped[str] = mapped_column(String(40), nullable=False, default="draft", index=True)
    sent_to_client_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    approved_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
    approved_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    accepted_mode: Mapped[str | None] = mapped_column(String(40), nullable=True, index=True)
    accepted_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
    accepted_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    accepted_ip: Mapped[str | None] = mapped_column(String(80), nullable=True)
    accepted_user_agent: Mapped[str | None] = mapped_column(String(500), nullable=True)
    acceptance_declaration_text: Mapped[str | None] = mapped_column(Text, nullable=True)
    otp_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
    pdf_hash_sha256: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    manual_signed_file_path: Mapped[str | None] = mapped_column(String(1000), nullable=True)
    manual_signed_file_hash_sha256: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
    manual_verified_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
    manual_verified_at_utc: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    rejection_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)



class ClientBusinessUnit(CommonBase):
    __tablename__ = "client_business_units"
    __table_args__ = (
        UniqueConstraint("tenant_id", "client_id", "business_code", name="uq_cbu_tenant_client_code"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
    client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    business_code: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    business_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
    trade_name: Mapped[str | None] = mapped_column(String(200), nullable=True)
    nature_of_business: Mapped[str | None] = mapped_column(String(200), nullable=True)
    is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, index=True)
    created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    updated_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)


class ClientBranch(CommonBase):
    __tablename__ = "client_branches"
    __table_args__ = (
        UniqueConstraint("tenant_id", "business_unit_id", "branch_code", name="uq_cbranch_tenant_business_code"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    tenant_id: Mapped[int] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False, index=True)
    client_id: Mapped[int] = mapped_column(ForeignKey("clients.id", ondelete="CASCADE"), nullable=False, index=True)
    business_unit_id: Mapped[int] = mapped_column(ForeignKey("client_business_units.id", ondelete="CASCADE"), nullable=False, index=True)
    branch_code: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
    branch_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
    branch_type: Mapped[str] = mapped_column(String(40), nullable=False, default="branch", index=True)
    address_line_1: Mapped[str | None] = mapped_column(String(255), nullable=True)
    address_line_2: Mapped[str | None] = mapped_column(String(255), nullable=True)
    city: Mapped[str | None] = mapped_column(String(100), nullable=True)
    state: Mapped[str | None] = mapped_column(String(100), nullable=True)
    pincode: Mapped[str | None] = mapped_column(String(20), nullable=True)
    is_primary: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, index=True)
    created_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    updated_by_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    created_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at_utc: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
