"""案件上下文查询工具 — 从MySQL查询案件信息"""

import asyncio
import logging

from app.agent.tools.decorator import tool

logger = logging.getLogger(__name__)


def _run_async(coro):
    """在同步上下文中运行异步协程"""
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None

    if loop and loop.is_running():
        # We're inside an async event loop — create a new one in a thread
        import concurrent.futures
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
            future = pool.submit(asyncio.run, coro)
            return future.result(timeout=10)
    else:
        return asyncio.run(coro)


async def _query_case_from_db(case_id: str) -> str:
    """从MySQL查询案件信息并格式化返回"""
    try:
        from ...core.database import get_pool
        pool = await get_pool()
    except Exception as e:
        logger.warning(f"Database pool unavailable: {e}")
        return f"[案件查询] 数据库不可用：{e}"

    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            # Query case basic info
            await cur.execute(
                "SELECT case_number, title, cause, filing_date, source, case_type, "
                "illegal_fact_summary, status "
                "FROM cases WHERE id = %s LIMIT 1",
                (case_id,),
            )
            case_row = await cur.fetchone()

            if not case_row:
                return f"[案件查询] 未找到案件 ID={case_id}"

            case = dict(case_row)

            # Query case parties
            await cur.execute(
                "SELECT party_name, party_type, legal_rep, contact_phone, id_number, address "
                "FROM case_parties WHERE case_id = %s",
                (case_id,),
            )
            party_rows = await cur.fetchall()
            parties = [dict(r) for r in party_rows]

    # Format result
    parts = []
    parts.append(f"案件编号：{case.get('case_number', '未知')}")
    parts.append(f"案件名称：{case.get('title', '未知')}")
    parts.append(f"案由：{case.get('cause', '未知')}")
    parts.append(f"立案日期：{case.get('filing_date', '未知')}")
    parts.append(f"案件来源：{case.get('source', '未知')}")
    parts.append(f"案件类型：{case.get('case_type', '未知')}")
    parts.append(f"案件状态：{case.get('status', '未知')}")

    illegal_facts = case.get('illegal_fact_summary', '')
    if illegal_facts:
        parts.append(f"违法事实摘要：{illegal_facts}")

    if parties:
        parts.append("")
        parts.append("当事人信息：")
        for i, p in enumerate(parties, 1):
            party_type_map = {"individual": "个人", "organization": "单位", "legal_person": "法人"}
            ptype = party_type_map.get(p.get('party_type', ''), p.get('party_type', '未知'))
            parts.append(f"  当事人{i}（{ptype}）：{p.get('party_name', '未知')}")
            if p.get('legal_rep'):
                parts.append(f"    法定代表人：{p['legal_rep']}")
            if p.get('contact_phone'):
                parts.append(f"    联系电话：{p['contact_phone']}")
            if p.get('id_number'):
                parts.append(f"    证件号码：{p['id_number']}")
            if p.get('address'):
                parts.append(f"    地址：{p['address']}")

    return "\n".join(parts)


@tool
def query_case_context(case_id: str) -> str:
    """查询案件上下文信息，从数据库获取案件详情和当事人信息。

    用于在Agent对话中注入当前案件的完整上下文，包括案件编号、案由、
    违法事实摘要、当事人信息等，辅助法律分析和文书生成。

    Args:
        case_id: 案件ID
    """
    try:
        return _run_async(_query_case_from_db(case_id))
    except Exception as e:
        logger.exception(f"query_case_context error for case_id={case_id}: {e}")
        return f"[案件查询] 查询失败：{e}"
