import argparse

import psycopg
from src.infrastructure.clients.cognito_idp_client import CognitoIdpClient
from src.infrastructure.credential_manager import CredentialManager
from src.logger import logger
from src.settings import Settings
from src.usecases.tenant_usecase import TenantUseCase

settings = Settings()


def main(legal_name: str, name: str | None, whi_customer_ids: list[str], cydas_customer_ids: list[str]) -> None:
    logger.info(f"LEGAL_NAME: {legal_name}")
    logger.info(f"NAME: {name}")
    logger.info(f"WHI_CUSTOMER_IDS: {whi_customer_ids}")
    logger.info(f"CYDAS_CUSTOMER_IDS: {cydas_customer_ids}")

    if not settings.user_pool_id:
        raise ValueError("USER_POOL_ID is not set")

    with psycopg.connect(conninfo=settings.postgres_url, autocommit=True) as connection:
        usecase = TenantUseCase.create(
            connection=connection,
            credential_manager=CredentialManager(
                client=CognitoIdpClient(user_pool_id=settings.user_pool_id),
            ),
        )

        tenant = usecase.issue(
            legal_name=legal_name,
            name=name,
            whi_customer_ids=whi_customer_ids,
            cydas_customer_ids=cydas_customer_ids,
        )

        logger.info(f"TENANT_ID: {tenant.id}")
        logger.info(f"APPLICATION_CLIENT_ID: {tenant.m2m_application_client_id}")


def __string_list(input_str: str) -> list[str]:
    return [s.strip() for s in input_str.split(",") if s.strip()]


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Tenant Creator Script")
    parser.add_argument(
        "--legal-name",
        type=str,
        required=True,
    )
    parser.add_argument(
        "--name",
        type=str,
        default=None,
        required=False,
    )
    parser.add_argument(
        "--whi-customer-ids",
        type=__string_list,
        required=False,
        default=[],
        help="WHI Customer IDs",
    )
    parser.add_argument(
        "--cydas-customer-ids",
        type=__string_list,
        required=False,
        default=[],
        help="CYDAS Customer IDs",
    )

    args = parser.parse_args()
    main(
        legal_name=args.legal_name,
        name=args.name,
        whi_customer_ids=args.whi_customer_ids,
        cydas_customer_ids=args.cydas_customer_ids,
    )
