import os
import json
import re

base_dir = "."  # execution from the project root
departments = [d for d in os.listdir(base_dir) 
               if os.path.isdir(os.path.join(base_dir, d)) 
               and d != "js" and d != "node_modules"]

vault_data = []

# Mapping departments to Etsy categories
DEPT_TO_CATEGORY = {
    '01_EXECUTIVE_AND_STRATEGY': 'Executive & Strategy',
    '02_SALES_AND_LEAD_GEN': 'Lead Machine',
    '03_MARKETING_AND_ADS': 'Content Factory',
    '04_SEO_AND_CONTENT': 'Content Factory',
    '05_COPYWRITING': 'Content Factory',
    '06_SOCIAL_MEDIA': 'Content Factory',
    '07_CUSTOMER_SUPPORT': '24/7 Receptionist',
    '08_SOFTWARE_ENGINEERING': 'Autopilot',
    '09_DATA_ANALYTICS': 'Autopilot',
    '10_UI_UX_DESIGN': 'Content Factory',
    '11_PRODUCT_MANAGEMENT': 'Executive & Strategy',
    '12_HR_AND_RECRUITING': 'Lead Machine',
    '13_FINANCE_AND_ACCOUNTING': 'Executive & Strategy',
    '14_LEGAL_AND_COMPLIANCE': 'Executive & Strategy',
    '15_IT_OPS_AND_SECURITY': 'Autopilot',
    '16_ECOMMERCE_OPS': 'Lead Machine',
    '17_RESEARCH_AND_DEVELOPMENT': 'Autopilot',
    '18_CLAUDE_PRO_DIRECTORY': 'Lead Machine'
}

print("Building Skills Vault...")

for dept in departments:
    dept_path = os.path.join(base_dir, dept)
    for skill_folder in os.listdir(dept_path):
        skill_path = os.path.join(dept_path, skill_folder)
        skill_md_path = os.path.join(skill_path, "SKILL.md")
        
        if os.path.isfile(skill_md_path):
            try:
                with open(skill_md_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # Extracting the name
                name_match = re.search(r'^#\s+(.+)$', content, re.MULTILINE)
                skill_name = name_match.group(1).strip() if name_match else skill_folder.replace('-', ' ').title()
                
                # Extracting the description (frontmatter or first paragraph)
                desc_match = re.search(r'description:\s*["\']?(.+?)["\']?\s*(?:$|\n)', content)
                if desc_match:
                    description = desc_match.group(1).strip()
                else:
                    # first paragraph after the title
                    lines = content.split('\n')
                    start = False
                    description = ""
                    for line in lines:
                        if start and line.strip() and not line.startswith('#'):
                            description = line.strip()[:150]
                            break
                        if line.startswith('# '):
                            start = True
                    if not description:
                        description = "Specialized agent to automate your tasks."
                
                # Category (Use the department name)
                category = dept
                
                # Tag (based on the skill folder name)
                tag = skill_folder.replace('-', ' ').title()
                
                # Relative path
                rel_path = f"{dept}/{skill_folder}"
                
                vault_data.append({
                    "n": skill_name,
                    "p": rel_path,
                    "c": category,
                    "t": tag,
                    "d": description,
                    "content": content
                })
            except Exception as e:
                pass

# Writing vault.js
vault_js_content = f"const SKILLS_VAULT = {json.dumps(vault_data, indent=2)};"
os.makedirs("js", exist_ok=True)
with open(os.path.join("js", "vault.js"), "w", encoding="utf-8") as f:
    f.write(vault_js_content)

print(f"Vault built! {len(vault_data)} skills indexed in js/vault.js.")