"""T5.5 规则写侧 repo 单测（C3 扩 / PRODUCT_SPEC §7 POST /rules）。

`RuleWriteRepo.create` 插一行 `rules`（level + content，绑 project_id），只 flush 不 commit
（提交交端点事务，与项目其它写侧 repo 一致）。`level` 合法性（global/genre/style/project）
由端点/schema 校验；repo 只负责写。纯内存 fake，无 DB。
"""

from __future__ import annotations

import uuid
from dataclasses import dataclass, field

import pytest
from pydantic import ValidationError
from ww_core.domain.rule_repo import RuleListItemView, RuleWriteRepo, RuleWriteView

PROJECT = uuid.UUID("00000000-0000-0000-0000-000000000001")


@dataclass
class _FakeRuleWriteRepo:
    rows: list[RuleWriteView] = field(default_factory=list)
    flushed: int = 0

    async def create(self, project_id: uuid.UUID, *, level: str, content: str) -> RuleWriteView:
        view = RuleWriteView(id=uuid.uuid4(), project_id=project_id, level=level, content=content)
        self.rows.append(view)
        self.flushed += 1
        return view

    async def list_for_project(self, project_id: uuid.UUID) -> list[RuleListItemView]:
        return [
            RuleListItemView(id=r.id, level=r.level, content=r.content)
            for r in self.rows
            if r.project_id == project_id
        ]

    async def delete(self, project_id: uuid.UUID, rule_id: uuid.UUID) -> bool:
        for r in self.rows:
            if r.id == rule_id and r.project_id == project_id:
                self.rows.remove(r)
                return True
        return False


@pytest.mark.asyncio
async def test_create_returns_view() -> None:
    repo: RuleWriteRepo = _FakeRuleWriteRepo()

    view = await repo.create(PROJECT, level="project", content="主角不许复活")

    assert view.level == "project"
    assert view.content == "主角不许复活"
    assert view.project_id == PROJECT


def test_rule_view_is_frozen() -> None:
    view = RuleWriteView(id=uuid.uuid4(), project_id=PROJECT, level="global", content="x")
    with pytest.raises(ValidationError):
        view.content = "y"
