"""Database overrides with bundled defaults and atomic, revision-checked publishing.""" import hashlib from pathlib import Path from uuid import uuid4 from app.core.request_context import get_request_id from app.models.system_log import AuditLog from app.models.system_setting import SystemSetting from app.models.user import User from app.schemas.compute_configuration import ComputeConfiguration from app.services.compute_catalog import COUNTRY_CATALOG from fastapi import HTTPException from sqlalchemy import select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession CATEGORY = "compute_comparison" DEFAULT_PATH = Path(__file__).with_name("compute_history_defaults.json") DEFAULT_CONFIGURATION = ComputeConfiguration.model_validate_json(DEFAULT_PATH.read_text()) DEFAULT_REVISION = hashlib.sha256(DEFAULT_PATH.read_bytes()).hexdigest() def default_envelope() -> dict: return { "config": DEFAULT_CONFIGURATION.model_dump(mode="json"), "revision": DEFAULT_REVISION, "is_default": True, } async def read_configuration(db: AsyncSession) -> dict: record = ( await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY)) ).scalar_one_or_none() return dict(record.payload) if record else default_envelope() def configuration_response(envelope: dict) -> dict: return { **envelope, "countries": [ {key: country[key] for key in ("code", "name", "name_en")} for country in COUNTRY_CATALOG ], } async def publish_configuration( db: AsyncSession, *, revision: str, config: ComputeConfiguration, actor: User, reset: bool = False, ) -> dict: # The unique category plus row lock also serializes concurrent first writes. await db.execute( insert(SystemSetting) .values(category=CATEGORY, payload=default_envelope()) .on_conflict_do_nothing(index_elements=[SystemSetting.category]) ) record = ( await db.execute( select(SystemSetting).where(SystemSetting.category == CATEGORY).with_for_update() ) ).scalar_one() if record.payload["revision"] != revision: await db.rollback() raise HTTPException(409, "Configuration changed. Reload before saving your edits.") envelope = ( default_envelope() if reset else { "config": config.model_dump(mode="json"), "revision": uuid4().hex, "is_default": reset, } ) before = record.payload if reset: await db.delete(record) else: record.payload = envelope # Audit and configuration commit together: a published edit must be attributable. db.add( AuditLog( actor_id=actor.id, actor_name=actor.username, action="compute_comparison.reset" if reset else "compute_comparison.update", target_type="system_setting", target_id=CATEGORY, result="success", request_id=get_request_id(), details={"before": before, "after": envelope}, ) ) await db.commit() return envelope