<?php
/**
 * Simple PO to MO compiler in pure PHP.
 */

function compile_po_to_mo($po_file, $mo_file) {
    if (!file_exists($po_file)) {
        echo "Warning: File $po_file does not exist.\n";
        return false;
    }
    
    $po_content = file_get_contents($po_file);
    // Matches msgid and msgstr (supporting multi-line strings)
    preg_match_all('/msgid\s+((?:".*"\s*)+)\s+msgstr\s+((?:".*"\s*)+)/', $po_content, $matches, PREG_SET_ORDER);
    
    $items = array();
    foreach ($matches as $match) {
        // Clean up multiline strings and quotes
        $id = preg_replace('/"\s+"/', '', trim($match[1]));
        $id = substr($id, 1, -1);
        $id = stripcslashes($id);
        
        $str = preg_replace('/"\s+"/', '', trim($match[2]));
        $str = substr($str, 1, -1);
        $str = stripcslashes($str);
        
        if ($id === '') {
            continue; // Skip metadata header
        }
        $items[$id] = $str;
    }
    
    ksort($items); // MO keys must be sorted alphabetically
    
    $num_strings = count($items);
    $ids = array_keys($items);
    $strs = array_values($items);
    
    $ids_table = '';
    $strs_table = '';
    $ids_offsets = array();
    $strs_offsets = array();
    
    // Header size: 28 bytes
    // Table of offsets: 8 bytes per string (length + offset)
    // Table of translations: 8 bytes per string (length + offset)
    $current_offset = 28 + ($num_strings * 8) * 2;
    
    for ($i = 0; $i < $num_strings; $i++) {
        $len = strlen($ids[$i]);
        $ids_offsets[] = array($len, $current_offset);
        $ids_table .= $ids[$i] . "\0";
        $current_offset += $len + 1;
    }
    
    for ($i = 0; $i < $num_strings; $i++) {
        $len = strlen($strs[$i]);
        $strs_offsets[] = array($len, $current_offset);
        $strs_table .= $strs[$i] . "\0";
        $current_offset += $len + 1;
    }
    
    $output = pack('I7', 
        0x950412de, // magic number
        0,          // revision
        $num_strings,
        28,         // offset of original table
        28 + ($num_strings * 8), // offset of translation table
        0, 0        // hash table size & offset
    );
    
    foreach ($ids_offsets as $offset) {
        $output .= pack('II', $offset[0], $offset[1]);
    }
    
    foreach ($strs_offsets as $offset) {
        $output .= pack('II', $offset[0], $offset[1]);
    }
    
    $output .= $ids_table . $strs_table;
    
    if (file_put_contents($mo_file, $output) !== false) {
        echo "Compiled $po_file successfully to $mo_file (" . count($items) . " strings).\n";
        return true;
    } else {
        echo "Error: Could not write $mo_file.\n";
        return false;
    }
}

// Compile files in current directory
$dir = dirname(__FILE__);
compile_po_to_mo("$dir/vi.po", "$dir/vi.mo");
compile_po_to_mo("$dir/en_US.po", "$dir/en_US.mo");
compile_po_to_mo("$dir/en_GB.po", "$dir/en_GB.mo");

