"""
Organization Profile Model
Captures business context to improve matching accuracy
"""

from typing import Optional, Dict, Any, List
from sqlalchemy import Column, String, JSON, Float, DateTime, Index, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
import uuid
from ..db import Base


class OrgProfile(Base):
    __tablename__ = "org_profiles"
    __allow_unmapped__ = (
        True  # Silence SQLAlchemy 2.0 warnings until migration to Mapped[]
    )

    id: str = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
    account_id: str = Column(
        String, ForeignKey("accounts.id"), unique=True, index=True, nullable=False
    )

    # Basic org info
    domain: Optional[str] = Column(String, index=True)  # Primary domain from signup
    company_name: Optional[str] = Column(String)

    # Industry classification
    industry: Optional[str] = Column(
        String
    )  # healthcare_provider, manufacturing, software_saas, finance, retail, education
    sub_industry: Optional[str] = Column(
        String
    )  # hospital_system, medical_device, etc.

    # Sales characteristics
    sales_motion: Optional[str] = Column(String)  # B2B, B2C, B2B2C
    target_segments: Optional[List[str]] = Column(
        JSON
    )  # ["hospitals", "clinics", "pharmacies"]
    typical_deal_size: Optional[str] = Column(
        String
    )  # small, medium, large, enterprise

    # Data characteristics
    hierarchy_complexity: Optional[str] = Column(String)  # low, medium, high
    geo_focus: Optional[Dict[str, Any]] = Column(
        JSON
    )  # {"countries": ["US"], "states": ["CA", "TX"]}
    avg_records_per_account: Optional[str] = Column(String)  # few, moderate, many

    # External data
    data_providers_in_use: Optional[List[str]] = Column(
        JSON
    )  # ["definitive_healthcare", "zoominfo", "apollo"]
    known_identifiers: Optional[List[str]] = Column(
        JSON
    )  # ["NPI__c", "DUNS__c", "HIN__c"]
    multi_brand_indicators: Optional[List[str]] = Column(
        JSON
    )  # ["Banner", "Sutter", "Kaiser"]

    # Confidence and source
    profile_confidence: float = Column(Float, default=0.5)  # 0-1 confidence score
    source_evidence: Optional[List[Dict[str, Any]]] = Column(
        JSON
    )  # [{"source": "signup", "field": "domain", "value": "...", "confidence": 0.9}]
    user_confirmed: Dict[str, Any] = Column(
        JSON, default=dict
    )  # {"confirmed_at": "...", "confirmed_by": "..."}

    # Timestamps
    created_at: datetime = Column(DateTime, default=datetime.utcnow)
    updated_at: datetime = Column(
        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
    )

    # Relationships
    account: Optional[Any] = relationship("Account", back_populates="org_profile")

    __table_args__ = (
        Index("idx_org_profile_industry", "industry"),
        Index("idx_org_profile_confidence", "profile_confidence"),
        {"extend_existing": True},
    )
