import json
import os
import sys
import argparse
from datetime import datetime

# Configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
REGISTRY_FILE = os.path.join(BASE_DIR, "manual_registry.json")

# Audience Mapping
LEVEL_MAP = {
    0: "ITGCLI",  # Cliente/Leigo
    1: "ITGSUP",  # Service Desk/Suporte
    2: "ITGINF",  # Infraestrutura
    3: "ITGENG"   # Engenharia
}

def load_registry():
    if not os.path.exists(REGISTRY_FILE):
        print(f"Error: Registry file not found at {REGISTRY_FILE}")
        sys.exit(1)
    try:
        with open(REGISTRY_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading registry: {e}")
        sys.exit(1)

def save_registry(data):
    try:
        with open(REGISTRY_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
    except Exception as e:
        print(f"Error saving registry: {e}")
        sys.exit(1)

def generate_code(level, title, author="Agente iT Guys"):
    if level not in LEVEL_MAP:
        print(f"Error: Invalid credentials level {level}. Must be 0-3.")
        sys.exit(1)

    audience_code = LEVEL_MAP[level]
    registry = load_registry()
    
    if audience_code not in registry:
        # Should not happen if JSON is initialized correctly, but safety net
        registry[audience_code] = {"next_id": 1, "manuals": []}

    current_id = registry[audience_code]["next_id"]
    year = datetime.now().strftime("%y")
    
    # Format: ITG[AUDIENCE] [XXXX]/[YEAR]
    # Example: ITGCLI 0001/26
    manual_code = f"{audience_code} {current_id:04d}/{year}"
    
    # Record metadata
    manual_entry = {
        "code": manual_code,
        "id": current_id,
        "title": title,
        "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "author": author
    }
    
    registry[audience_code]["manuals"].append(manual_entry)
    registry[audience_code]["next_id"] += 1
    
    save_registry(registry)
    
    print(f"SUCCESS: Generated Code: {manual_code}")
    print(f"Details: {json.dumps(manual_entry, indent=2, ensure_ascii=False)}")
    return manual_code

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Generate unique manual codes for iT Guys.")
    parser.add_argument("--level", type=int, required=True, choices=[0, 1, 2, 3], help="Manual Level (0=Client, 1=Support, 2=Infra, 3=Eng)")
    parser.add_argument("--title", type=str, required=True, help="Title of the manual")
    parser.add_argument("--author", type=str, default="João Pedro Toledo Gonçalves", help="Author name")

    args = parser.parse_args()
    
    generate_code(args.level, args.title, args.author)
