# ========== 服务端新增接口 ==========
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, text
from typing import Dict, List
import pandas as pd

app = FastAPI()

db_dict = {
    # mysql-阿里云
    "mysql": {
        'host': 'rm-wz9yg9bsb2zf01ea4yo.mysql.rds.aliyuncs.com',
        "driver": "pymysql",
        'port': 3306,
        'user': 'XP_Yswg2025',
        'password': 'VPaaDe2R1MKqvzq2YSpcxu',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # pg爬虫库-内网
    "postgresql_14": {
        'host': '192.168.10.223',
        "driver": "psycopg2",
        'port': 5433,
        'user': 'postgres',
        'password': 'F9kL2sXe81rZq',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # pg爬虫库-外网
    "postgresql_14_outer": {
        'host': '61.145.136.61',
        "driver": "psycopg2",
        'port': 54328,
        'user': 'postgres',
        'password': 'F9kL2sXe81rZq',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # pg正式库-内网
    "postgresql_15": {
        'host': '192.168.10.224',
        "driver": "psycopg2",
        'port': 5433,
        'user': 'postgres',
        'password': 'F9kL2sXe81rZq',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # pg正式库-外网
    "postgresql_15_outer": {
        'host': '113.100.143.162',
        "driver": "psycopg2",
        'port': 5433,
        'user': 'postgres',
        'password': 'F9kL2sXe81rZq',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # pg集群-内网
    "postgresql_cluster": {
        'host': '192.168.10.155',
        "driver": "psycopg2",
        'port': 6432,
        'user': 'postgres',
        'password': 'G8m!Q2p9D#f%5x',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # pg集群-外网
    "postgresql_cluster_outer": {
        'host': '113.100.143.162',
        "driver": "psycopg2",
        'port': 6432,
        'user': 'postgres',
        'password': 'G8m!Q2p9D#f%5x',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
    # doris集群-内网
    "doris": {
        'host': '192.168.10.151',
        "driver": "pymysql",
        'port': 49030,
        'user': 'fangxingjun',
        'password': 'fangxingjun12345',
        'database': 'selection',
        'charset': 'utf8mb4',
    },
}

db_engines: Dict[str, any] = {
    "main": create_engine("mysql+pymysql://user:password@host1/db_main", pool_size=20),
    "analytics": create_engine("mysql+pymysql://user:password@host2/db_analytics", pool_size=15),
    "legacy": create_engine("postgresql://user:password@host3/db_legacy", pool_size=10),
}

class QueryRequest(BaseModel):
    db: str
    sql: str

class InsertRequest(BaseModel):
    db: str
    table: str
    if_exists: str = "append"
    data: List[dict]

class TransactionRequest(BaseModel):
    db: str
    sql_list: List[str]

@app.post("/query")
def query_db(req: QueryRequest):
    if req.db not in db_engines:
        raise HTTPException(status_code=400, detail="Unknown database alias")
    engine = db_engines[req.db]
    try:
        with engine.connect() as conn:
            rows = conn.execute(text(req.sql)).fetchall()
            return {"result": [dict(r) for r in rows]}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/insert")
def insert_data(req: InsertRequest):
    if req.db not in db_engines:
        raise HTTPException(status_code=400, detail="Unknown database alias")
    engine = db_engines[req.db]
    try:
        df = pd.DataFrame(req.data)
        df.to_sql(req.table, con=engine, if_exists=req.if_exists, index=False)
        return {"success": True, "rows_written": len(df)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/transaction")
def handle_transaction(req: TransactionRequest):
    if req.db not in db_engines:
        raise HTTPException(status_code=400, detail="Unknown DB")
    engine = db_engines[req.db]
    try:
        with engine.begin() as conn:
            for sql in req.sql_list:
                conn.execute(text(sql))
        return {"success": True, "sql_executed": len(req.sql_list)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))