#!/usr/bin/env python3

import os

def main():
    progress_file = '../Progress/progress.md'

    # Read the progress file
    with open(progress_file, 'r') as f:
        lines = f.readlines()

    # Find table start
    table_start = None
    for i, line in enumerate(lines):
        if line.strip().startswith('| Primary Folder'):
            table_start = i
            break

    if table_start is None:
        print("Table header not found")
        return

    header_lines = lines[:table_start + 1]

    # Collect data lines
    data_lines = []
    i = table_start + 1
    while i < len(lines) and lines[i].strip().startswith('|'):
        data_lines.append(lines[i])
        i += 1

    rest_lines = lines[i:]

    # Parse existing entries
    existing = {}
    for line in data_lines:
        parts = [p.strip() for p in line.split('|')[1:-1]]
        if len(parts) >= 3:
            key = (parts[0], parts[1], parts[2])
            existing[key] = line

    # Find all PHP files
    php_files = []
    for root, dirs, files in os.walk('../vmserver10/intranet'):
        for file in files:
            if file.endswith('.php'):
                full_path = os.path.join(root, file)
                rel_path = os.path.relpath(full_path, '../vmserver10/intranet')
                parts = rel_path.split(os.sep)
                if len(parts) == 1:
                    primary, folder, fname = '', '', parts[0]
                elif len(parts) == 2:
                    primary, folder, fname = parts[0], '', parts[1]
                elif len(parts) >= 3:
                    primary, folder, fname = parts[0], parts[1], os.sep.join(parts[2:])
                else:
                    continue
                php_files.append((primary, folder, fname))

    # New entries
    new_entries = [t for t in php_files if t not in existing]

    # All entries
    all_entries = list(existing.keys()) + new_entries
    all_entries.sort(key=lambda x: (x[0], x[1], x[2]))

    # Write back
    with open(progress_file, 'w') as f:
        f.writelines(header_lines)
        for entry in all_entries:
            if entry in existing:
                f.write(existing[entry])
            else:
                f.write(f'| {entry[0]} | {entry[1]} | {entry[2]} | no | No | No\n')
        f.writelines(rest_lines)

if __name__ == '__main__':
    main()