from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

import pymysql
import yaml

SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from runtime_config import (
    DEFAULT_CONFIG_KEY,
    DEFAULT_CONFIG_PATH,
    DEFAULT_CONFIG_TABLE,
)


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Create/update cepconfiguration row from config.yaml.")
    p.add_argument("--config", default=str(DEFAULT_CONFIG_PATH))
    p.add_argument("--config-table", default=DEFAULT_CONFIG_TABLE)
    p.add_argument("--config-key", default=DEFAULT_CONFIG_KEY)
    p.add_argument("--mysql-host", default="192.168.138.182")
    p.add_argument("--mysql-port", type=int, default=3306)
    p.add_argument("--mysql-user", default="ceptest")
    p.add_argument("--mysql-password", default="ck@123456")
    p.add_argument("--mysql-database", default="ckc_cep_db_test")
    return p.parse_args()


def mysql_conn_kwargs(args: argparse.Namespace) -> dict[str, Any]:
    return {
        "host": args.mysql_host,
        "port": int(args.mysql_port),
        "user": args.mysql_user,
        "password": args.mysql_password,
        "database": args.mysql_database,
        "charset": "utf8mb4",
        "cursorclass": pymysql.cursors.DictCursor,
        "autocommit": False,
    }


def main() -> None:
    args = parse_args()
    cfg_path = Path(args.config).resolve()
    cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8"))
    cfg_json = json.dumps(cfg, ensure_ascii=False)

    table = args.config_table
    key = args.config_key

    conn = pymysql.connect(**mysql_conn_kwargs(args))
    try:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT COLUMN_NAME
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=%s
                """,
                (table,),
            )
            cols = {str(r["COLUMN_NAME"]).lower() for r in (cur.fetchall() or [])}

            if {"key", "value"}.issubset(cols):
                cur.execute(
                    f"""
                    INSERT INTO `{table}` (`key`, `value`, `createddate`, `updateddate`, `conment`)
                    VALUES (%s, %s, NOW(), NOW(), %s)
                    ON DUPLICATE KEY UPDATE
                      `value`=VALUES(`value`),
                      `updateddate`=NOW()
                    """,
                    (key, cfg_json, "vip-report runtime config"),
                )
            elif {"config_key", "config_json"}.issubset(cols):
                cur.execute(
                    f"""
                    INSERT INTO `{table}` (config_key, config_json)
                    VALUES (%s, %s)
                    ON DUPLICATE KEY UPDATE
                      config_json=VALUES(config_json),
                      updated_at=CURRENT_TIMESTAMP
                    """,
                    (key, cfg_json),
                )
            else:
                raise RuntimeError(
                    f"Unsupported table schema for `{table}`. "
                    f"Need (key,value) or (config_key,config_json), actual={sorted(cols)}"
                )
        conn.commit()
    finally:
        conn.close()

    print(
        json.dumps(
            {
                "ok": True,
                "table": table,
                "config_key": key,
                "source_config": str(cfg_path),
            },
            ensure_ascii=False,
        )
    )


if __name__ == "__main__":
    main()
