"""Write YouTube stream key into repo config/youtube.ini while preserving other keys.""" from __future__ import annotations import configparser import io import re from pathlib import Path from src.config_governance import save_managed_file def _youtube_sync_relpaths(root: Path, process: str | None = None) -> list[str]: relpaths = ["youtube.ini"] if process: safe = re.sub(r"[^a-zA-Z0-9_.-]", "_", process.strip()) if safe: relpaths.append(f"youtube.{safe}.ini") elif (root / "config" / "youtube.youtube.ini").is_file(): relpaths.append("youtube.youtube.ini") return relpaths def write_youtube_ini_stream_key(repo_root: Path, stream_key_or_url: str, process: str | None = None) -> str: root = repo_root.resolve() value = (stream_key_or_url or "").strip() if not value: return "sync skipped: empty youtube_rtmp_key" written: list[str] = [] for rel in _youtube_sync_relpaths(root, process): cfg_path = root / "config" / rel cfg_path.parent.mkdir(parents=True, exist_ok=True) parser = configparser.ConfigParser() if cfg_path.is_file(): parser.read(cfg_path, encoding="utf-8-sig") if not parser.has_section("youtube"): parser.add_section("youtube") parser.set("youtube", "key", value) buf = io.StringIO() parser.write(buf) save_managed_file("app-config", rel, buf.getvalue()) written.append(str(cfg_path)) return f"wrote {', '.join(written)}"