"""Persistent student profile (ФИО + группа) and DOCX metadata defaults.""" from __future__ import annotations import json import logging from dataclasses import dataclass, field from pathlib import Path from .diagram_includes import app_dir from .doc_metadata import DocumentMetadata _log = logging.getLogger(__name__) USER_PROFILE_FILENAME = "md2gost.user.json" @dataclass class UserProfile: student: str = "" group: str = "" metadata: DocumentMetadata = field(default_factory=DocumentMetadata) def is_complete(self) -> bool: return bool(self.student.strip() and self.group.strip()) def user_profile_path(base: Path | None = None) -> Path: return (base or app_dir()) / USER_PROFILE_FILENAME def load_user_profile(base: Path | None = None) -> UserProfile: path = user_profile_path(base) if not path.is_file(): return UserProfile() try: raw = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: _log.warning("Не удалось прочитать %s: %s", path, exc) return UserProfile() if not isinstance(raw, dict): return UserProfile() return UserProfile( student=str(raw.get("student") or "").strip(), group=str(raw.get("group") or "").strip(), metadata=DocumentMetadata.from_dict(raw.get("metadata")), ) def save_user_profile(profile: UserProfile, base: Path | None = None) -> Path: path = user_profile_path(base) path.parent.mkdir(parents=True, exist_ok=True) meta = profile.metadata or DocumentMetadata() data = { "student": (profile.student or "").strip(), "group": (profile.group or "").strip(), "metadata": meta.to_dict(), } path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return path