"""
Organization Profile API endpoints
"""

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Dict, Any, Optional
from pydantic import BaseModel

from ...db import get_session
from ...auth import get_current_account, get_current_user
from ...services.context_service import ContextService

router = APIRouter(prefix="/api/v2/org-profile", tags=["org-profile"])


class OrgProfileUpdate(BaseModel):
    industry: Optional[str] = None
    sub_industry: Optional[str] = None
    sales_motion: Optional[str] = None
    target_segments: Optional[list] = None
    hierarchy_complexity: Optional[str] = None
    geo_focus: Optional[dict] = None
    data_providers_in_use: Optional[list] = None
    known_identifiers: Optional[list] = None


@router.get("")
async def get_org_profile(
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
) -> Dict[str, Any]:
    """Get organization profile"""
    # STUBBED: Return empty profile to prevent frontend crashes
    # TODO: Implement actual profile retrieval
    return {
        "profile": None,
        "suggestions": {
            "weight_adjustments": {},
            "blocking_strategy": "standard",
            "threshold_adjustments": {},
        },
    }


@router.post("/confirm")
async def confirm_profile(
    updates: OrgProfileUpdate,
    db: AsyncSession = Depends(get_session),
    account_id: str = Depends(get_current_account),
    user_id: str = Depends(get_current_user),
) -> Dict[str, Any]:
    """Confirm and update organization profile"""
    service = ContextService(db)

    # Convert Pydantic model to dict, excluding None values
    update_dict = updates.dict(exclude_none=True)

    profile = await service.update_from_user_confirmation(
        account_id, update_dict, user_id
    )

    return {
        "status": "confirmed",
        "profile_confidence": profile.profile_confidence,
        "updates_applied": list(update_dict.keys()),
    }


@router.get("/industries")
async def get_available_industries() -> Dict[str, list]:
    """Get list of available industries and sub-industries"""
    return {
        "industries": [
            {
                "value": "healthcare_provider",
                "label": "Healthcare Provider",
                "sub_industries": ["hospital_system", "clinic", "specialty"],
            },
            {
                "value": "manufacturing",
                "label": "Manufacturing",
                "sub_industries": ["automotive", "aerospace", "industrial"],
            },
            {
                "value": "software_saas",
                "label": "Software & SaaS",
                "sub_industries": ["crm", "erp", "martech"],
            },
            {
                "value": "finance",
                "label": "Financial Services",
                "sub_industries": ["banking", "insurance", "investment"],
            },
            {
                "value": "education",
                "label": "Education",
                "sub_industries": ["higher_ed", "k12", "training"],
            },
        ]
    }
