import psycopg2
from jinja2 import Environment, FileSystemLoader
import os

def generate_portal_index():
    db_params = {'host': 'localhost', 'user': 'initium20', 'password': 'straconX260706', 'dbname': 'strx_docs'}
    template_dir = os.path.join(os.path.dirname(__file__), 'templates')
    env = Environment(loader=FileSystemLoader(template_dir))
    template = env.get_template('portal_template.html')

    try:
        conn = psycopg2.connect(**db_params)
        cur = conn.cursor()
        
        # Get categories and counts
        cur.execute("SELECT category, COUNT(*) FROM modules GROUP BY category ORDER BY category;")
        categories = cur.fetchall()
        
        # Get all modules
        cur.execute("SELECT technical_name, display_name, summary, author, version, category FROM modules ORDER BY display_name;")
        modules = []
        for row in cur.fetchall():
            modules.append({
                'technical_name': row[0],
                'display_name': row[1],
                'summary': row[2],
                'author': row[3],
                'version': row[4],
                'category': row[5],
                'url': f'generated/{row[0]}/index.html'
            })
        
        cur.close()
        conn.close()

        output_path = '/odoo20/strx_tools/docs/index.html'
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(template.render(categories=categories, modules=modules))
        print(f"Portal index generated at {output_path}")

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    generate_portal_index()
