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 ShareDraft
from app.models.user import User
from app.services.share_draft_service import ShareDraftService


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_share_draft_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_share_draft=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="share_draft",
                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()

        draft = ShareDraftService.generate_for_session(db, user=user, session=session)

        assert "实修分享稿草稿" in draft.content
        assert "自定义模板" in draft.content
        assert "系统不会自动发送到任何群" in draft.content
        assert "不代表结论" in draft.content
        assert "情绪和身体反应" not in draft.content
        assert "做了什么功课" not in draft.content
        assert "当下的一点变化" not in draft.content
        assert "我看见自己不敢表达" in draft.content
        assert db.get(TopicSession, 1).share_draft_generated == 1
        assert db.query(ShareDraft).count() == 1

        copied = ShareDraftService.mark_copied(db, user=user, draft_id=draft.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:
            ShareDraftService.delete(db, user=other_user, draft_id=draft.id)
        assert error.value.status_code == 404
        assert db.get(ShareDraft, draft.id) is not None

        ShareDraftService.delete(db, user=user, draft_id=draft.id)
        assert db.get(ShareDraft, draft.id) is None
