from __future__ import annotations from types import SimpleNamespace import pytest from backend.dto.common import ApiError from backend.services.profile_card_service import ProfileCardService from backend.services.workflow_service import WorkflowService from core.audit_service import AuditService from core.identity import RequestContext from database.db_helper import Database, DatabaseSettings, SqliteSettings from database.repositories.image_repository import ImageRepository from database.repositories.profile_card_repository import ProfileCardRepository from database.repositories.profile_repository import ProfileRepository from database.repositories.workflow_repository import WorkflowRepository def _fixture(tmp_path): database = Database( DatabaseSettings( backend="sqlite", sqlite=SqliteSettings(path=str(tmp_path / "profile-card.sqlite3")), ) ) database.initialize() profiles = ProfileRepository(database) workflows = WorkflowRepository(database) images = ImageRepository(database) audit = AuditService(database) ctx = RequestContext.system("profile-card-test") profiles.create( { "profile_id": "profile-card-owner", "name": "Card owner", "owner_platform": "webui", "owner_user_id": "system", "status": "active", "metadata": {}, } ) detail = WorkflowService(workflows, profiles, audit).create_workflow( "profile-card-owner", { "workflow_id": "workflow-card", "workflow_type": "character_gradual", "display_name": "Detailed card flow", "status": "running", "metadata": {}, }, ctx, ) nodes = {node.node_key: node for node in detail.nodes} roles = { "avatar": "headshot", "persona_image": "design_sheet", "standing": "full_body", "pv": "style_lock", } assets: dict[str, str] = {} for role, node_key in roles.items(): image_id = f"image-{role}" image = images.create( { "image_id": image_id, "profile_id": "profile-card-owner", "workflow_id": "workflow-card", "node_id": nodes[node_key].node_id, "image_uri": f"storage://images/{image_id}.png", "is_selected": True, "metadata": {}, } ) workflows.update_node( nodes[node_key].node_id, {"status": "selected", "selected_image_id": image.image_id}, ) assets[role] = image.image_id for node in detail.nodes: if node.node_key in roles.values() or node.node_key in {"final_pack", "profile_card"}: continue workflows.update_node(node.node_id, {"status": "completed"}) service = ProfileCardService( cards=ProfileCardRepository(database), profiles=profiles, workflows=workflows, images=images, audit_service=audit, ) return service, profiles, workflows, images, database, ctx, assets def test_finalize_creates_card_assets_updates_avatar_and_archives_workflow_atomically(tmp_path) -> None: service, profiles, workflows, _images, database, ctx, assets = _fixture(tmp_path) payload = { "idempotency_key": "finalize-card-1", "persona_document": "A stable character bible.", "assets": assets, } card = service.finalize("workflow-card", payload, ctx) replay = service.finalize("workflow-card", payload, ctx) assert replay.card_id == card.card_id assert {asset.asset_role for asset in card.assets} == {"avatar", "persona_image", "standing", "pv"} profile = profiles.get("profile-card-owner") assert profile.avatar_image_uri == "storage://images/image-avatar.png" assert profile.profile_category == "profile_card" assert profile.generation_kind == "detailed" assert profile.detailed_workflow_state == "archived" workflow = workflows.get_workflow("workflow-card") assert workflow.status == "archived" assert workflow.metadata["profile_card_id"] == card.card_id node = next(item for item in workflows.list_nodes("workflow-card") if item.node_key == "profile_card") assert node.status == "completed" conn = database.connect() try: card_count = conn.execute("SELECT COUNT(*) AS total FROM character_profile_cards").fetchone()["total"] history_count = conn.execute( "SELECT COUNT(*) AS total FROM workflow_history WHERE action = 'profile_card_finalized'" ).fetchone()["total"] finally: conn.close() assert card_count == 1 assert history_count == 1 assert service.list_for_profile("profile-card-owner", ctx)[0].card_id == card.card_id def test_missing_asset_role_does_not_archive_workflow(tmp_path) -> None: service, _profiles, workflows, _images, _database, ctx, assets = _fixture(tmp_path) assets.pop("pv") with pytest.raises(ApiError) as captured: service.finalize( "workflow-card", { "idempotency_key": "finalize-card-missing", "persona_document": "Character bible", "assets": assets, }, ctx, ) assert captured.value.details["missing_roles"] == ["pv"] assert workflows.get_workflow("workflow-card").status == "running" def test_finalization_rejects_cross_branch_and_restricted_assets(tmp_path) -> None: service, _profiles, workflows, images, _database, ctx, assets = _fixture(tmp_path) full_body = next(node for node in workflows.list_nodes("workflow-card") if node.node_key == "full_body") foreign_node = workflows.create_node( { "node_id": "node-other-branch-full", "workflow_id": "workflow-card", "node_key": "full_body", "title": "Other branch full body", "status": "selected", "branch_name": "other", "selected_image_id": "image-other-branch", "sort_order": full_body.sort_order, "metadata": {}, } ) images.create( { "image_id": "image-other-branch", "profile_id": "profile-card-owner", "workflow_id": "workflow-card", "node_id": foreign_node.node_id, "image_uri": "storage://images/other-branch.png", "is_selected": True, "metadata": {}, } ) cross_branch_assets = {**assets, "standing": "image-other-branch"} with pytest.raises(ApiError) as cross_branch: service.finalize( "workflow-card", { "idempotency_key": "finalize-card-cross-branch", "persona_document": "Character bible", "assets": cross_branch_assets, }, ctx, ) assert cross_branch.value.details["active_branch"] == "main" images.update("image-pv", {"metadata": {"gallery_visibility": "restricted"}}) with pytest.raises(ApiError) as restricted: service.finalize( "workflow-card", { "idempotency_key": "finalize-card-restricted", "persona_document": "Character bible", "assets": assets, }, ctx, ) assert restricted.value.details["asset_role"] == "pv" assert workflows.get_workflow("workflow-card").status == "running" def test_repository_failure_rolls_back_card_profile_workflow_node_and_history(tmp_path, monkeypatch) -> None: service, profiles, workflows, _images, database, ctx, assets = _fixture(tmp_path) monkeypatch.setattr( "backend.services.profile_card_service.uuid4", lambda: SimpleNamespace(hex="duplicate"), ) with pytest.raises(Exception): service.finalize( "workflow-card", { "idempotency_key": "finalize-card-rollback", "persona_document": "Character bible", "assets": assets, }, ctx, ) assert profiles.get("profile-card-owner").avatar_image_uri is None assert workflows.get_workflow("workflow-card").status == "running" profile_card_node = next(node for node in workflows.list_nodes("workflow-card") if node.node_key == "profile_card") assert profile_card_node.status == "draft" conn = database.connect() try: assert conn.execute("SELECT COUNT(*) AS total FROM character_profile_cards").fetchone()["total"] == 0 assert conn.execute("SELECT COUNT(*) AS total FROM character_profile_card_assets").fetchone()["total"] == 0 assert conn.execute( "SELECT COUNT(*) AS total FROM workflow_history WHERE action = 'profile_card_finalized'" ).fetchone()["total"] == 0 finally: conn.close() def test_legacy_final_archive_is_exposed_as_read_only_card_and_classified(tmp_path) -> None: service, profiles, workflows, _images, _database, ctx, assets = _fixture(tmp_path) workflow = workflows.get_workflow("workflow-card") workflows.update_workflow( "workflow-card", { "status": "archived", "metadata": { **workflow.metadata, "branch_state": { "main": { "final_archive_schema_version": "2026-07-09.final-archive.v1", "final_archive_history_id": "history-legacy", "final_archive_image_ids": list(assets.values()), "final_archive_completed_at": "2026-07-15 00:00:00", } }, }, }, ) cards = service.list_for_profile("profile-card-owner", ctx) assert len(cards) == 1 assert cards[0].status == "legacy_read_only" assert cards[0].read_only is True assert service.get(cards[0].card_id, ctx).card_id == cards[0].card_id profile = profiles.get("profile-card-owner") assert profile.profile_category == "profile_card" assert profile.detailed_workflow_state == "archived" def test_legacy_final_pack_and_hires_fix_node_keys_can_finalize(tmp_path) -> None: service, _profiles, _workflows, _images, database, ctx, assets = _fixture(tmp_path) conn = database.connect() try: conn.execute("UPDATE workflow_nodes SET node_key = 'final_pack' WHERE workflow_id = 'workflow-card' AND node_key = 'profile_card'") conn.execute("UPDATE workflow_nodes SET node_key = 'hires_fix' WHERE workflow_id = 'workflow-card' AND node_key = 'style_lock'") conn.commit() finally: conn.close() card = service.finalize( "workflow-card", { "idempotency_key": "finalize-card-legacy-keys", "persona_document": "Character bible", "assets": assets, }, ctx, ) assert card.status == "sealed" def test_profile_card_routes_are_registered() -> None: from backend.route_registry import ROUTES routes = {(route.method, route.endpoint, route.handler) for route in ROUTES} assert ( "POST", "workflows/{workflow_id}/finalize-card", "backend.routes.profile_card_routes.finalize_profile_card", ) in routes assert ( "GET", "profiles/{profile_id}/profile-cards", "backend.routes.profile_card_routes.list_profile_cards", ) in routes assert ( "GET", "profile-cards/{card_id}", "backend.routes.profile_card_routes.get_profile_card", ) in routes def test_profile_card_migration_is_idempotent_and_declared(tmp_path) -> None: from database.models import TABLES database = Database( DatabaseSettings( backend="sqlite", sqlite=SqliteSettings(path=str(tmp_path / "profile-card-migration.sqlite3")), ) ) database.initialize() database.initialize() conn = database.connect() try: tables = { str(row["name"]) for row in conn.execute( "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'character_profile_card%'" ).fetchall() } finally: conn.close() assert tables == {"character_profile_cards", "character_profile_card_assets"} assert {"character_profile_cards", "character_profile_card_assets"}.issubset( {table.name for table in TABLES} )