# import psycopg2
import logging
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool

# h6_pg_us = {
#     'user': 'postgres',
#     'password': 'fazAqRRVV9vDmwDNRNb593ht5TxYVrfTyHJSJ3BS',
#     'host': '113.100.143.162',
#     'port': 5432,
#     'database': 'selection',
#     # 'encoding': 'utf-8',
# }

h6_pg_us = {
    'user': 'postgres',
    # 'password': urllib.parse.quote('T#4$4%qPbR7mJx'),
    'password': "F9kL2sXe81rZq",
    'host': "113.100.143.162",
    'port': 5432,
    'database': 'selection',
    # 'encoding': 'utf-8',
}


def get_14pg_country_engine(site_name="us"):
    h14_pg_us = {
        "user": "postgres",
        # "password": urllib.parse.quote("G8m!Q2p9D#f%5x"),
        "password": "F9kL2sXe81rZq",
        "host": "61.145.136.61",
        "port": 54328,
        "database": "selection",
    }
    if site_name not in ['uk', 'fr', 'es', 'it', 'de']:
        h14_pg_us["database"] = f"selection"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h14_pg_us.values())
    else:
        h14_pg_us["database"] = f"selection_{site_name}"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h14_pg_us.values())
    # engine = create_engine(db_, poolclass=NullPool, connect_args={'connect_timeout': 10})  # , pool_recycle=3600
    engine = create_engine(db_, pool_timeout=300, connect_args={'connect_timeout': 10})  # , pool_recycle=3600
    return engine


def get_pg_country_engine(site_name="us"):
    if site_name not in ['uk', 'fr', 'es', 'it', 'de']:
        h6_pg_us["database"] = f"selection"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h6_pg_us.values())
    else:
        h6_pg_us["database"] = f"selection_{site_name}"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h6_pg_us.values())
    # engine = create_engine(db_, poolclass=NullPool, connect_args={'connect_timeout': 10})  # , pool_recycle=3600
    engine = create_engine(db_, pool_timeout=300, connect_args={'connect_timeout': 10})  # , pool_recycle=3600
    return engine


def get_pg_con(site_name="us"):
    if site_name not in ['uk', 'fr', 'es', 'it', 'de']:
        h6_pg_us["database"] = f"selection"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h6_pg_us.values())
    else:
        h6_pg_us["database"] = f"selection_{site_name}"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h6_pg_us.values())
    engine = create_engine(db_, poolclass=NullPool, connect_args={'connect_timeout': 10})
    conn = engine.connect()
    return conn


def get_14pg_psy_country_engine(site_name="us"):
    if site_name not in ['uk', 'fr', 'es', 'it', 'de']:
        database = f"selection"
    else:
        database = f"selection_{site_name}"
    engine = psycopg2.connect(
        dbname=database,
        user="postgres",
        password="G8m!Q2p9D#f%5x",
        host="61.145.136.61",
        port="54328",
        connect_timeout=300,
    )
    return engine


def get_6pg_psy_country_engine(site_name="us"):
    if site_name not in ['uk', 'fr', 'es', 'it', 'de']:
        database = f"selection"
    else:
        database = f"selection_{site_name}"
    engine = psycopg2.connect(
        dbname=database,
        user="postgres",
        password="G8m!Q2p9D#f%5x",
        host="113.100.143.162",
        port="5432",
        connect_timeout=300,
    )
    return engine


# @func_set_timeout(300)
def updatas_pg_asin(sql, data=None, site="us", db='pg14'):
    engine = get_14pg_psy_country_engine(site) if db == 'pg14' else get_6pg_psy_country_engine()
    try:
        cur = engine.cursor()
        if data!= None:
            cur.executemany(sql, data)
        else:
            cur.execute(sql)
        # msg = execute_values(psycopg2.extensions.cursor(engine), sql, data, page_size=1000)
        # print(msg, data[0][0:2])
        engine.commit()
    except psycopg2.OperationalError as e:
        logging.info(f"失败sql为 {sql} {e}")
        return False
    except Exception as e:
        logging.info(f"失败sql为 {sql} {e}")
        return False
    finally:
        engine.close()
        return True


# async def insert_data(sql, data=None, site="us", db='pg14'):
#     # Establish a connection to the PostgreSQL database
#     async with asyncpg.create_pool(**h6_pg_us) as pool:
#         # Execute the insert statements concurrently
#         async with pool.acquire() as conn:
#             async with conn.transaction():
#                 await conn.executemany(sql, data)



