import requests
import sys
import os
sys.path.append('/app')
from prefect import flow, task, get_run_logger


@task
def create_kyc_in_odoo(team_id: str, team_name: str, owner_id: str, logto_org_id: str = ""):
    """Create KYC request in Odoo via FastAPI"""
    logger = get_run_logger()
    
    odoo_url = "http://odoo:8069/fastapi/kyc/order"
    
    kyc_data = {
        "team_id": team_id,
        "team_name": team_name,
        "owner_id": owner_id,
        "logto_org_id": logto_org_id
    }
    
    try:
        response = requests.post(
            odoo_url,
            json=kyc_data,
            headers={"Content-Type": "application/json"},
            auth=("kyc_api", "kyc_api_pass"),
            timeout=30
        )
        
        response.raise_for_status()
        result = response.json()
        
        logger.info(f"Created KYC in Odoo: {result}")
        
        if not result.get("success"):
            raise Exception(f"Odoo API error: {result}")
            
        return result
        
    except Exception as e:
        logger.error(f"Error creating KYC in Odoo: {e}")
        raise


@flow(name="team-created")
def team_created_flow(team_id: str, team_name: str, owner_id: str, logto_org_id: str = ""):
    """Process team creation - create KYC request in Odoo"""
    logger = get_run_logger()
    
    logger.info(f"Processing team creation: {team_name} (ID: {team_id})")
    
    # Create KYC request in Odoo
    kyc_result = create_kyc_in_odoo(team_id, team_name, owner_id, logto_org_id)
    
    logger.info(f"Team {team_name} processed successfully. KYC ID: {kyc_result.get('kyc_id')}")
    
    return {
        "team_id": team_id,
        "team_name": team_name,
        "kyc_id": kyc_result.get("kyc_id"),
        "kyc_reference": kyc_result.get("kyc_reference"),
        "status": "completed"
    }


@task
async def create_organization_in_logto(team_id: str, team_name: str, owner_id: str, company_name: str = ""):
    """Create organization in Logto and assign owner as admin"""
    logger = get_run_logger()
    
    try:
        # Import LogtoManagementClient (должен быть доступен через teams backend)
        teams_service_url = "http://teams-backend:8000"
        
        # Вызываем teams backend для создания организации
        create_org_data = {
            "team_id": team_id,
            "team_name": team_name,
            "owner_id": owner_id,
            "company_name": company_name or team_name
        }
        
        response = requests.post(
            f"{teams_service_url}/internal/create-organization",
            json=create_org_data,
            timeout=30
        )
        
        response.raise_for_status()
        result = response.json()
        
        logger.info(f"Created Logto organization: {result}")
        
        return result
        
    except Exception as e:
        logger.error(f"Error creating Logto organization: {e}")
        raise


@flow(name="create-organization-after-kyc-approval")
async def create_organization_after_kyc_approval(
    team_id: str, 
    team_name: str, 
    owner_id: str, 
    company_name: str = ""
):
    """Create Logto organization after KYC approval"""
    logger = get_run_logger()
    
    logger.info(f"Creating organization for approved KYC: {team_name} (Team ID: {team_id})")
    
    # Create organization in Logto
    org_result = await create_organization_in_logto(team_id, team_name, owner_id, company_name)
    
    logger.info(f"Organization creation completed for team {team_name}")
    
    return {
        "team_id": team_id,
        "team_name": team_name,
        "organization_id": org_result.get("organization_id"),
        "status": "completed"
    }


if __name__ == "__main__":
    # Для тестирования
    team_created_flow("test-team-123", "Test Team", "user-123")