from __future__ import annotations

from datetime import UTC, datetime

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

from app.models import Base
from app.models.ai_config import SystemConfig
from app.models.chat import ChatMessage, ChatSession, TopicSession
from app.models.entitlement import EntitlementPlan
from app.models.growth import GrowthProfileRevision, UserGrowthProfile
from app.models.user import User
from app.services.entitlement_service import EntitlementService
from app.services.growth_profile_service import GrowthProfileService
from app.services.rag_service import PromptService


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 _now() -> datetime:
    return datetime.now(UTC).replace(tzinfo=None)


def test_finish_topic_generates_summary_and_updates_growth_profile_for_enabled_plan():
    with _db() as db:
        db.add(SystemConfig(config_key="mock_model_enabled", config_value="true"))
        db.add(EntitlementPlan(id=10, name="深度陪伴版", plan_type="deep", monthly_topic_limit=90, enable_growth_profile=1, status=1))
        user = User(id=1, phone="13800000001", name="学员", daily_chat_limit=100, daily_chat_used=0)
        session = ChatSession(id=1, user_id=1, title="阴影人格", message_count=2, last_message_at=_now(), is_deleted=0)
        topic = TopicSession(
            id=1,
            user_id=1,
            chat_session_id=1,
            title="阴影人格练习",
            core_question="阴影人格练习步骤是什么",
            status="active",
            message_count=2,
            quota_deducted=1,
            started_at=_now(),
        )
        db.add_all([user, session, topic])
        db.add_all(
            [
                ChatMessage(id=1, session_id=1, topic_session_id=1, user_id=1, role="user", content="我做阴影人格会抗拒，身体发紧", created_at=_now()),
                ChatMessage(id=2, session_id=1, topic_session_id=1, user_id=1, role="assistant", content="先回到身体感受，观察抗拒，不急着分析。", created_at=_now()),
            ]
        )
        db.commit()
        EntitlementService.assign_user_plan(db, user=user, plan_id=10, operated_by=1)
        db.commit()

        result = GrowthProfileService.finish_active_topic(db, user=user, session=session)

        assert result["topic"]["status"] == "completed"
        assert result["summary"]["summary"]
        assert result["profile"] is not None
        assert "最近主题" in result["profile"]["profileText"]
        assert db.query(UserGrowthProfile).filter_by(user_id=1).count() == 1
        assert db.query(GrowthProfileRevision).filter_by(user_id=1).count() == 1


def test_prompt_can_include_growth_profile_context_without_replacing_knowledge_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(UserGrowthProfile(user_id=1, profile_text="用户最近反复在表达障碍和身体紧绷之间观察。"))
        db.commit()

        growth_context = GrowthProfileService.prompt_context(db, user)
        messages = PromptService.build_messages(
            db,
            "我现在又表达不出来了怎么办",
            [],
            growth_context=growth_context,
        )

        content = "\n".join(item["content"] for item in messages)
        assert "[长期成长档案]" in content
        assert "表达障碍" in content
        assert "[本轮可靠知识上下文]" in content
