import os
import sys
import re
import json

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from app.services.i18n import BUILTIN_TRANSLATIONS

def main():
    template_dir = os.path.join(os.path.dirname(__file__), "..", "app", "templates")
    keys_found = set()
    # Match {{ t('key') }} or {{ t("key") }} or {{ t('key', ...) }}
    t_pattern = re.compile(r"t\(\s*['\"]([^'\"]+?)['\"](?:\s*,\s*[^)]+?)?\s*\)")
    
    for root, _, files in os.walk(template_dir):
        for f in files:
            if f.endswith(".html"):
                path = os.path.join(root, f)
                with open(path, "r", encoding="utf-8", errors="ignore") as fp:
                    content = fp.read()
                    matches = t_pattern.findall(content)
                    for m in matches:
                        clean_key = m.strip()
                        # Ignore variable names, template syntax, or internal setting keys
                        if (
                            clean_key 
                            and not clean_key.startswith("privacy.")
                            and not clean_key.startswith("contact.")
                            and not clean_key.startswith("social.")
                            and not clean_key.startswith("donation.")
                            and not clean_key.startswith("{{")
                            and not clean_key.startswith("e.g.")
                            and clean_key not in {"en", "hi", "ur", "tab", "q", "type", "category", "state", "priority", "level", "notice", "appointment", "appreciation", "canvas", "iframe", "input", "permission", "recommendation", "youtube", "facebook", "instagram", "linkedin"}
                        ):
                            keys_found.add(clean_key)
                            
    hi_trans = BUILTIN_TRANSLATIONS.get("hi", {})
    ur_trans = BUILTIN_TRANSLATIONS.get("ur", {})
    
    missing_hi = [k for k in sorted(keys_found) if k not in hi_trans]
    missing_ur = [k for k in sorted(keys_found) if k not in ur_trans]
    
    output_data = {
        "total_keys": len(keys_found),
        "missing_hi_count": len(missing_hi),
        "missing_ur_count": len(missing_ur),
        "missing_hi": missing_hi,
        "missing_ur": missing_ur
    }
    
    out_path = os.path.join(os.path.dirname(__file__), "missing_keys.json")
    with open(out_path, "w", encoding="utf-8") as out_fp:
        json.dump(output_data, out_fp, ensure_ascii=False, indent=2)
        
    print(f"Extraction complete! Total keys: {len(keys_found)}, Missing HI: {len(missing_hi)}, Missing UR: {len(missing_ur)}")

if __name__ == "__main__":
    main()
