import json
import os
from datetime import datetime, timezone

def generate_vocabulary_import(
    category_name: str, 
    lang_first_id: int, 
    lang_second_id: int, 
    word_pairs: list,
    output_filename: str = "import_ready_vocab.json"
):
    """
    Generates a Polly-compatible JSON import file for a new vocabulary category,
    saving it in the same directory as this script.
    """
    
    # Generate a current timestamp in the exact ISO format Kotlin's Instant expects
    now_iso = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    
    # Base structure for a CategoryExport
    export_data = {
        "type": "Category",
        "exportDate": now_iso,
        "metadata": {
            "itemCount": len(word_pairs),
            "categoryCount": 1,
            "exportScope": f"Category: {category_name}"
        },
        "category": {
            "type": "TagCategory",
            "id": 99999,  # Dummy ID; your app's ID remapping will fix this on import
            "name": category_name
        },
        "items": [],
        "states": [],          # Left empty because these are brand new words
        "stageMappings": []
    }

    # Populate items and stage mappings
    start_id = 100000 
    
    for idx, (word_first, word_second) in enumerate(word_pairs, start=start_id):
        
        export_data["items"].append({
            "id": idx,
            "languageFirstId": lang_first_id,
            "languageSecondId": lang_second_id,
            "wordFirst": word_first,
            "wordSecond": word_second,
            "createdAt": now_iso,
            "features": "{}"  # Empty features block
        })
        
        export_data["stageMappings"].append({
            "vocabularyItemId": idx,
            "stage": "NEW"
        })

    # --- NEW: Get the directory of the current script and build the full path ---
    script_dir = os.path.dirname(os.path.abspath(__file__))
    full_output_path = os.path.join(script_dir, output_filename)

    # Save to file using the absolute path
    with open(full_output_path, 'w', encoding='utf-8') as f:
        json.dump(export_data, f, indent=2, ensure_ascii=False)
        
    print(f"Successfully generated {len(word_pairs)} items!")
    print(f"Saved to: {full_output_path}")


# --- Example Usage ---
if __name__ == "__main__":
    GERMAN_ID = 15
    PORTUGUESE_ID = 7
    
    new_words = [
        ("Krankenwagen", "ambulância"),
        ("Blutdruck", "pressão arterial"),
        ("Rollstuhl", "cadeira de rodas"),
        ("Fieberthermometer", "termômetro")
    ]
    
    generate_vocabulary_import(
        category_name="termos médicos - extra",
        lang_first_id=GERMAN_ID,
        lang_second_id=PORTUGUESE_ID,
        word_pairs=new_words,
        output_filename="polly_import_med_extra.json"
    )