import json
import os
import re
from collections import defaultdict

def main():
    template_dir = os.path.join(os.path.dirname(__file__), "..", "app", "templates")
    t_pattern = re.compile(r"t\(\s*['\"]([^'\"]+?)['\"](?:\s*,\s*[^)]+?)?\s*\)")
    
    file_keys = defaultdict(list)
    seen = set()
    
    # Priority order of templates
    priority_order = [
        "base.html",
        "public/index.html",
        "public/donate.html",
        "public/about.html",
        "public/pillars.html",
        "public/pillar_detail.html",
        "public/contact.html",
        "public/need_support.html",
        "public/volunteer.html",
        "public/jobs.html",
        "public/leadership.html",
        "public/ground_workers.html",
        "public/gallery.html",
        "public/activities.html",
        "public/grievance.html",
        "public/grievance_track.html",
        "public/application_status.html",
        "portal/dashboard.html",
        "auth/login.html",
        "auth/register.html",
    ]
    
    # First pass: check priority templates in order
    for rel_path in priority_order:
        path = os.path.join(template_dir, rel_path.replace("/", os.sep))
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8", errors="ignore") as fp:
                content = fp.read()
                matches = t_pattern.findall(content)
                for m in matches:
                    clean = m.strip()
                    if (
                        clean 
                        and not clean.startswith("privacy.")
                        and not clean.startswith("contact.")
                        and not clean.startswith("social.")
                        and not clean.startswith("donation.")
                        and not clean.startswith("{{")
                        and not clean.startswith("e.g.")
                        and clean not in {"en", "hi", "ur", "tab", "q", "type", "category", "state", "priority", "level", "notice", "appointment", "appreciation", "canvas", "iframe", "input", "permission", "recommendation", "youtube", "facebook", "instagram", "linkedin"}
                        and clean not in seen
                    ):
                        seen.add(clean)
                        file_keys[rel_path].append(clean)
                        
    # Second pass: any remaining templates
    for root, _, files in os.walk(template_dir):
        for f in files:
            if f.endswith(".html"):
                path = os.path.join(root, f)
                rel_path = os.path.relpath(path, template_dir).replace("\\", "/")
                with open(path, "r", encoding="utf-8", errors="ignore") as fp:
                    content = fp.read()
                    matches = t_pattern.findall(content)
                    for m in matches:
                        clean = m.strip()
                        if (
                            clean 
                            and not clean.startswith("privacy.")
                            and not clean.startswith("contact.")
                            and not clean.startswith("social.")
                            and not clean.startswith("donation.")
                            and not clean.startswith("{{")
                            and not clean.startswith("e.g.")
                            and clean not in {"en", "hi", "ur", "tab", "q", "type", "category", "state", "priority", "level", "notice", "appointment", "appreciation", "canvas", "iframe", "input", "permission", "recommendation", "youtube", "facebook", "instagram", "linkedin"}
                            and clean not in seen
                        ):
                            seen.add(clean)
                            file_keys[rel_path].append(clean)
                            
    out_file = os.path.join(os.path.dirname(__file__), "keys_by_template_ordered.json")
    with open(out_file, "w", encoding="utf-8") as out_fp:
        json.dump(file_keys, out_fp, ensure_ascii=False, indent=2)
        
    print(f"Total unique keys ordered: {len(seen)} across {len(file_keys)} templates")

if __name__ == "__main__":
    main()
