# -*- coding: utf-8 -*-
"""业务层 · 路演服务（发布审核规则）。"""
from __future__ import annotations

from fastapi import HTTPException

from ..infrastructure.repositories import Database


class RoadshowService:
    """路演发布：按发布主体与范围判定是否需审核。"""

    def __init__(self, db: Database):
        self.db = db

    def _need_review(self, user: dict, req) -> bool:
        role = user.get("role")
        if role == "operator":
            return False
        if role == "government":
            scope = user.get("scope_region_ids", [])
            if req.scope_type == "region" and req.region_id and req.region_id in scope:
                return False  # 自身权限范围内，免审
            return True       # 超出范围，需审核
        # 投资机构/载体/企业：一律需审核
        return True

    async def create(self, req, actor: dict) -> dict:
        """创建路演（含审核判定）。"""
        if not req.title.strip():
            raise HTTPException(status_code=400, detail="标题不能为空")
        if req.end_at and req.start_at and req.end_at < req.start_at:
            raise HTTPException(status_code=400, detail="结束时间不能早于开始时间")
        need_review = self._need_review(actor, req)
        fields = {
            **req.model_dump(exclude_none=True),
            "publisher_id": actor["id"],
            "publisher_role": actor.get("role", "investor"),
            "status": "submitted" if need_review else "published",
            "need_review": need_review,
        }
        return await self.db.roadshows.create(fields)
