from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
from odoo import api
from odoo.addons.fastapi.dependencies import odoo_env


router = APIRouter(tags=["partners"])


# ============================================================================
# Schemas
# ============================================================================


class CreateKycApplicationInput(BaseModel):
    workflow_id: str
    team_name: str
    owner_id: str
    owner_email: str = ""
    tax_id: str = ""
    registration_number: str = ""
    country_code: str = ""
    contact_person: str = ""
    contact_email: str = ""
    contact_phone: str = ""


class KycApplicationSchema(BaseModel):
    id: int
    name: str
    workflow_id: str
    team_name: str
    state: str


class BuyerSchema(BaseModel):
    id: int
    name: str
    uuid: str
    team_name: str
    logto_org_id: Optional[str]
    state: str


class SetLogtoOrgIdInput(BaseModel):
    logto_org_id: str


# ============================================================================
# KYC Application Endpoints
# ============================================================================


@router.post("/kyc/applications", response_model=KycApplicationSchema)
def create_kyc_application(
    data: CreateKycApplicationInput,
    env: api.Environment = Depends(odoo_env),
):
    """Create KYC application from Temporal workflow."""
    try:
        # Find country by code
        country = None
        if data.country_code:
            country = env['res.country'].sudo().search(
                [('code', '=', data.country_code.upper())],
                limit=1,
            )

        application = env['kyc.application'].sudo().create({
            'workflow_id': data.workflow_id,
            'team_name': data.team_name,
            'owner_id': data.owner_id,
            'tax_id': data.tax_id,
            'registration_number': data.registration_number,
            'country_id': country.id if country else False,
            'contact_person': data.contact_person,
            'contact_email': data.contact_email or data.owner_email,
            'contact_phone': data.contact_phone,
            'state': 'pending',
        })
        env.cr.commit()

        return KycApplicationSchema(
            id=application.id,
            name=application.name,
            workflow_id=application.workflow_id,
            team_name=application.team_name,
            state=application.state,
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/kyc/applications/{workflow_id}", response_model=KycApplicationSchema)
def get_kyc_application(
    workflow_id: str,
    env: api.Environment = Depends(odoo_env),
):
    """Get KYC application by workflow ID."""
    application = env['kyc.application'].search(
        [('workflow_id', '=', workflow_id)],
        limit=1,
    )
    if not application:
        raise HTTPException(status_code=404, detail="Application not found")

    return KycApplicationSchema(
        id=application.id,
        name=application.name,
        workflow_id=application.workflow_id,
        team_name=application.team_name,
        state=application.state,
    )


# ============================================================================
# Buyer Endpoints
# ============================================================================


@router.get("/buyers/{uuid}", response_model=BuyerSchema)
def get_buyer_by_uuid(
    uuid: str,
    env: api.Environment = Depends(odoo_env),
):
    """Get buyer by UUID."""
    buyer = env['buyer'].search(
        [('uuid', '=', uuid)],
        limit=1,
    )
    if not buyer:
        raise HTTPException(status_code=404, detail="Buyer not found")

    return BuyerSchema(
        id=buyer.id,
        name=buyer.name,
        uuid=buyer.uuid,
        team_name=buyer.team_name,
        logto_org_id=buyer.logto_org_id or None,
        state=buyer.state,
    )


@router.post("/buyers/{uuid}/logto-org")
def set_buyer_logto_org(
    uuid: str,
    data: SetLogtoOrgIdInput,
    env: api.Environment = Depends(odoo_env),
):
    """Set Logto organization ID on buyer (called by Temporal after org creation)."""
    buyer = env['buyer'].search(
        [('uuid', '=', uuid)],
        limit=1,
    )
    if not buyer:
        raise HTTPException(status_code=404, detail="Buyer not found")

    buyer.set_logto_org_id(data.logto_org_id)
    env.cr.commit()

    return {
        "success": True,
        "buyer_uuid": buyer.uuid,
        "logto_org_id": data.logto_org_id,
    }
