import requests
from loguru import logger
import os
import sys
from apscheduler.schedulers.blocking import BlockingScheduler
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)

from aidso_geo.utils import bh_utils

KEEP_FIELDS = (
    "prompt",
    "taskId",
    "reqId",
    "platform",
    "type",
    "thinkingEnabled",
    "channel",
)


def task_commit_api(task_data):
    req_id = task_data.get("reqId",'')
    prompt = task_data.get("prompt",'')
    platform = task_data.get("platform",'')
    channel = task_data.get("channel") or ""
    task_type = task_data.get("type",'')
    url = "http://172.16.1.223:8086/api/geo/task_commit"

    payload = {k: task_data.get(k) for k in KEEP_FIELDS }

    try:
        response = requests.post(url, json=payload)
        response_data = response.json()

        if response_data.get("code") == 200:
            task_data["status"] = "PROCESSING"
            bh_utils.insert_data("geo_third_task_data", [task_data])
            logger.success(f'{req_id}--{prompt}--{platform}--{channel}--{task_type}--提交成功')
    except Exception as e:
        logger.error(e)


def get_result_api(task_data):
    req_id = task_data.get("reqId",'')
    prompt = task_data.get("prompt",'')
    platform = task_data.get("platform",'')
    channel = task_data.get("channel") or ""
    task_type = task_data.get("type",'')
    url = f"http://172.16.1.223:8086/api/geo/task_check?reqId={req_id}"

    try:
        response = requests.get(url)
        response_data = response.json()
        print(response.text)
        data = response_data.get("data") or {}

        if response_data.get("code") == 200 and data.get("status") == "success":
            task_data["status"] = "SUCCESS"
            bh_utils.insert_data("geo_third_task_data", [task_data])
            logger.success(f'{req_id}--{prompt}--{platform}--{channel}--{task_type}--获取成功')
    except Exception as e:
        logger.error(e)


def query_task_commit():
    return bh_utils.query_data(
        "select * from geo_third_task_data where status = 'ING'"
    )



def query_task_check():
    return bh_utils.query_data(
        "select * from geo_third_task_data where status = 'PROCESSING'"
    )

def task_commit():
    commit_tasks = query_task_commit()
    if commit_tasks:
        for task in query_task_commit():
            task_commit_api(task)

def task_check():
    check_tasks = query_task_check()
    if check_tasks:
        for task in query_task_check():
            get_result_api(task)



if __name__ == "__main__":
    logger.info("调度 启动")
    scheduler = BlockingScheduler(timezone="Asia/Shanghai")
    # task_check()
    scheduler.add_job(
        task_commit,
        trigger="interval",
        seconds=30,
        id='third_task_commit',
        max_instances=1,
        coalesce=True,
        replace_existing=True
    )

    scheduler.add_job(
        task_check,
        trigger="interval",
        seconds=30,
        id='third_task_check',
        max_instances=1,
        coalesce=True,
        replace_existing=True
    )
    scheduler.start()
    logger.info("third_task_commit 启动")
    logger.info("third_task_check 启动")
#