import json import os from datetime import datetime def load_config(): """Loads config.json and ensures directories exist.""" try: with open("config.json", "r") as f: config = json.load(f) os.makedirs(config.get("DataDirectory", "./"), exist_ok=True) os.makedirs(config.get("PDFOutputDirectory", "./"), exist_ok=True) return config except FileNotFoundError: print("Error: config.json is missing. Please create it.") exit(1) except Exception as e: print(f"Error reading config: {e}") exit(1) def load_json(filepath, default_structure): """Loads a JSON file or creates it with a default structure if missing.""" if not os.path.exists(filepath): save_json(filepath, default_structure) return default_structure try: with open(filepath, "r") as f: return json.load(f) except json.JSONDecodeError: print(f"Warning: {filepath} is corrupted. Returning default structure.") return default_structure def save_json(filepath, data): """Saves data to a JSON file.""" try: with open(filepath, "w") as f: json.dump(data, f, indent=2) except Exception as e: print(f"File write failure for {filepath}: {e}") def get_next_id(prefix, current_records, id_field): """Generates the next sequential ID (e.g., CLT-001).""" if not current_records: return f"{prefix}-001" ids = [int(r[id_field].split("-")[1]) for r in current_records if r[id_field].startswith(prefix)] next_num = max(ids) + 1 if ids else 1 return f"{prefix}-{next_num:03d}"