from __future__ import annotations

import asyncio

from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool

from app.models import Base
from app.models.entitlement import EntitlementPlan
from app.models.growth import UserGrowthProfile
from app.models.user import User
from app.schemas.admin import AgentDebugRequest
from app.services.agent_debug_service import AgentDebugService


def _db() -> Session:
    engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False}, poolclass=StaticPool)
    Base.metadata.create_all(engine)
    return Session(engine)


def test_agent_debug_can_simulate_user_growth_profile_context():
    with _db() as db:
        user = User(id=1, phone="13800000001", name="测试学员", daily_chat_limit=100, daily_chat_used=0)
        db.add(user)
        db.add(
            EntitlementPlan(
                id=10,
                name="深度陪伴版",
                plan_type="deep",
                monthly_topic_limit=90,
                enable_growth_profile=1,
                status=1,
            )
        )
        db.add(UserGrowthProfile(user_id=1, profile_text="用户在表达障碍主题上反复出现身体紧绷。"))
        db.commit()

        result = asyncio.run(
            AgentDebugService.build_result(
                db,
                AgentDebugRequest(
                    promptContent="你是测试 Agent",
                    modelId=1,
                    userId=1,
                    question="我又表达不出来了怎么办",
                ),
            )
        )

        rendered = "\n".join(item["content"] for item in result.messages)
        assert "[长期成长档案]" in rendered
        assert "表达障碍" in rendered
        assert result.tool_trace[0]["tool"] == "load_debug_user_context"
        assert result.tool_trace[0]["response"]["growthProfileUsed"] is True

