from __future__ import annotations

from datetime import UTC, datetime

import pytest
from fastapi import HTTPException
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 ContentGenerationConfig
from app.models.chat import ChatMessage, ChatSession, TopicSession
from app.models.entitlement import EntitlementPlan
from app.models.growth import TeacherHelpCard
from app.models.user import User
from app.services.help_card_service import HelpCardService


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_generate_help_card_from_topic_summary_and_mark_copied():
    with _db() as db:
        user = User(id=1, phone="13800000001", name="测试学员", daily_chat_limit=100, daily_chat_used=0)
        plan = EntitlementPlan(id=10, name="基础版", plan_type="basic", allow_help_card=1, status=1)
        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, plan, session, topic])
        db.add(
            ContentGenerationConfig(
                config_type="help_card",
                template_content="【给老师的求助卡·自定义模板】\n问题：{{issue}}\n摘要：{{summary}}",
                instruction_content="只整理用户明确表达的内容",
                change_type="save",
                updated_by=1,
            )
        )
        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()

        card = HelpCardService.generate_for_session(db, user=user, session=session)

        assert "给老师的求助卡" in card.content
        assert "自定义模板" in card.content
        assert "不会自动发送给老师" in card.content
        assert "阴影人格练习步骤是否正确" in card.content
        assert "情绪 / 身体感受" not in card.content
        assert "已经尝试过或被建议的功课" not in card.content
        assert db.get(TopicSession, 1).help_card_generated == 1
        assert db.query(TeacherHelpCard).count() == 1

        copied = HelpCardService.mark_copied(db, user=user, card_id=card.id)

        assert copied.copied == 1
        assert copied.copied_at is not None

        other_user = User(id=2, phone="13800000002", name="其他学员", daily_chat_limit=100, daily_chat_used=0)
        db.add(other_user)
        db.commit()
        with pytest.raises(HTTPException) as error:
            HelpCardService.delete(db, user=other_user, card_id=card.id)
        assert error.value.status_code == 404
        assert db.get(TeacherHelpCard, card.id) is not None

        HelpCardService.delete(db, user=user, card_id=card.id)
        assert db.get(TeacherHelpCard, card.id) is None
