import argparse
import os
import subprocess

import psycopg
import psycopg.conninfo

USER_POOL_ID = os.getenv("USER_POOL_ID")
POSTGRES_HOST = os.getenv("POSTGRES_HOST")
POSTGRES_PORT = os.getenv("POSTGRES_PORT")
POSTGRES_USER = os.getenv("POSTGRES_USER")
POSTGRES_PASSWORD = os.getenv("POSTGRES_PASSWORD")
POSTGRES_DB = os.getenv("POSTGRES_DB")


def main(stage: str, client_name: str, client_stage: str) -> None:
    client_id = __insert(
        client_name=client_name,
        client_stage=client_stage,
    )
    print("Created client with ID:", client_id)

    # クライアントを新規作成する時は必ずAPIキーも作成する運用のため
    subprocess.run(
        [  # noqa: S607
            "python",
            "client_api_key_creator.py",
            "--stage",
            stage,
            "--client-id",
            str(client_id),
            "--client-name",
            client_name,
            "--client-stage",
            client_stage,
        ],
        check=True,
    )


def __insert(
    client_name: str,
    client_stage: str,
) -> str:
    postgres_url = psycopg.conninfo.make_conninfo(
        host=POSTGRES_HOST,
        port=POSTGRES_PORT,
        user=POSTGRES_USER,
        password=POSTGRES_PASSWORD,
        dbname=POSTGRES_DB,
    )
    with psycopg.connect(postgres_url) as conn, conn.cursor() as cur:
        cur.execute(
            """--sql
            INSERT INTO clients (name, stage)
            VALUES (%(client_name)s, %(client_stage)s)
            RETURNING id;
            """,
            {
                "client_name": client_name,
                "client_stage": client_stage,
            },
        )
        conn.commit()
        client = cur.fetchone()
        if client:
            return client[0]  # id

        raise Exception("Failed to insert client")  # noqa: TRY002


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Client API Key Creator Script")
    parser.add_argument(
        "--stage",
        type=str,
        required=True,
    )
    parser.add_argument(
        "--client-name",
        type=str,
        required=True,
    )
    parser.add_argument(
        "--client-stage",
        type=str,
        required=True,
    )

    args = parser.parse_args()
    main(
        stage=args.stage,
        client_name=args.client_name,
        client_stage=args.client_stage,
    )
