<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Khanfar System Update Publisher</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .input-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        input[type="text"], textarea {
            width: calc(100% - 20px);
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        textarea {
            height: 100px;
            resize: vertical;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button.red {
            background-color: #dc3545;
        }
        button.red:hover {
            background-color: #c82333;
        }
        .file-list {
            margin-top: 10px;
            padding: 10px;
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
            max-height: 200px;
            overflow-y: auto;
        }
        .file-item {
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .version-display {
            font-size: 16px;
            font-weight: bold;
            margin: 10px 0;
            color: #333;
        }
        .status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Khanfar System Update Publisher</h1>
        
        <div class="section">
            <div class="input-group">
                <label>Base Code Directory:</label>
                <input type="text" id="baseCodeInput" readonly>
                <button onclick="selectBaseCode()">Select Base Code</button>
            </div>
            <div id="baseCodeFiles" class="file-list"></div>
        </div>

        <div class="section">
            <div class="version-display">
                Current Version: <span id="currentVersion">Unknown</span>
            </div>
            <div class="version-display">
                Customer Version: <span id="customerVersion">Not Selected</span>
            </div>
            <div class="version-display">
                GitHub Version: <span id="githubVersion">Checking...</span>
                <button onclick="checkGithubVersion()" style="padding: 5px; margin-left: 10px;">↻</button>
            </div>
            <button onclick="startReset()" class="red">Reset Version to 1.0.1</button>
            <button onclick="selectCustomerCodeAndReset()" id="selectCustomerBtn" style="display: none;" class="red">Step 2: Select Customer Code (Optional)</button>
            <button onclick="completeReset()" id="completeResetBtn" style="display: none;" class="red">Complete Reset</button>
        </div>

        <div class="section">
            <div class="input-group">
                <label>Select Files to Update:</label>
                <button onclick="selectFiles()">Select Files</button>
                <button onclick="clearSelection()">Clear Selection</button>
                <div id="selectedFiles" class="file-list"></div>
            </div>
        </div>

        <div class="section">
            <div class="input-group">
                <label>New Version:</label>
                <input type="text" id="newVersion" placeholder="Enter new version number">
            </div>
            <div class="input-group">
                <label>Changelog:</label>
                <textarea id="changelog" placeholder="Enter changelog information"></textarea>
            </div>
        </div>

        <div class="section">
            <div id="progress" class="status">Ready</div>
            <button onclick="publishUpdate()" id="publishButton">Publish Update</button>
        </div>
    </div>

    <script>
        // GitHub configuration
        const GITHUB_TOKEN = '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';
        const GITHUB_OWNER = 'khanfar';
        const GITHUB_REPO = 'khanfar-sys-updates';

        // Function to create/update file on GitHub
        async function updateGitHubFile(path, content, message) {
            const url = `https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/contents/${path}`;
            
            // Function to safely encode content to base64
            function safeBase64Encode(str) {
                // Convert the string to UTF-8 bytes
                const bytes = new TextEncoder().encode(str);
                // Convert bytes to base64
                let binary = '';
                bytes.forEach(byte => binary += String.fromCharCode(byte));
                return btoa(binary);
            }

            try {
                // First try to get the file to get its SHA if it exists
                const response = await fetch(url, {
                    headers: {
                        'Authorization': `token ${GITHUB_TOKEN}`,
                        'Accept': 'application/vnd.github.v3+json'
                    }
                });
                
                let sha = null;
                if (response.ok) {
                    const data = await response.json();
                    sha = data.sha;
                }

                // Prepare the request body
                const body = {
                    message: message,
                    content: safeBase64Encode(content)
                };

                if (sha) {
                    body.sha = sha;
                }

                // Create or update the file
                const updateResponse = await fetch(url, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `token ${GITHUB_TOKEN}`,
                        'Accept': 'application/vnd.github.v3+json',
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(body)
                });

                if (!updateResponse.ok) {
                    throw new Error(`GitHub API error: ${updateResponse.status}`);
                }
            } catch (err) {
                throw new Error(`Failed to update GitHub file: ${err.message}`);
            }
        }

        let baseCodeHandle = null;
        let customerCodeHandle = null;
        let selectedFiles = [];
        let currentVersion = '0.0.0';
        let customerVersion = 'Not Selected';

        // Check for File System Access API support
        if (!('showDirectoryPicker' in window)) {
            alert('Your browser does not support the File System Access API. Please use Chrome or Edge.');
        }

        async function selectBaseCode() {
            try {
                baseCodeHandle = await window.showDirectoryPicker();
                document.getElementById('baseCodeInput').value = baseCodeHandle.name;
                await loadCurrentVersion();
                await listDirectoryContents(baseCodeHandle, 'baseCodeFiles');
                enableUI(true);
            } catch (err) {
                showStatus('Error selecting base code directory: ' + err.message, true);
            }
        }

        async function loadCurrentVersion() {
            try {
                const versionFile = await baseCodeHandle.getFileHandle('version.py');
                const file = await versionFile.getFile();
                const text = await file.text();
                const versionMatch = text.match(/return ["'](.+?)["']/);
                if (versionMatch) {
                    currentVersion = versionMatch[1];
                    document.getElementById('currentVersion').textContent = currentVersion;
                    
                    // Calculate and set the recommended next version
                    const versionParts = currentVersion.split('.');
                    versionParts[2] = (parseInt(versionParts[2]) + 1).toString();
                    const recommendedVersion = versionParts.join('.');
                    
                    document.getElementById('newVersion').value = recommendedVersion;
                    document.getElementById('newVersion').placeholder = `Recommended: ${recommendedVersion}`;
                }
            } catch (err) {
                showStatus('Error loading version: ' + err.message, true);
            }
        }

        async function selectFiles() {
            if (!baseCodeHandle) {
                showStatus('Please select base code directory first', true);
                return;
            }

            try {
                const fileHandles = await window.showOpenFilePicker({
                    multiple: true
                });

                selectedFiles = await Promise.all(fileHandles.map(async handle => {
                    const file = await handle.getFile();
                    return {
                        handle: handle,
                        name: file.name,
                        path: file.webkitRelativePath || file.name
                    };
                }));

                updateFileDisplay();
            } catch (err) {
                showStatus('Error selecting files: ' + err.message, true);
            }
        }

        function clearSelection() {
            selectedFiles = [];
            updateFileDisplay();
        }

        function updateFileDisplay() {
            const fileList = document.getElementById('selectedFiles');
            fileList.innerHTML = selectedFiles.map(file => 
                `<div class="file-item">${file.path}</div>`
            ).join('');
        }

        async function calculateHash(file) {
            const buffer = await file.arrayBuffer();
            const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
            const hashArray = Array.from(new Uint8Array(hashBuffer));
            return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        }

        function enableUI(enabled) {
            const buttons = document.querySelectorAll('button');
            buttons.forEach(button => button.disabled = !enabled);
        }

        function showStatus(message, isError = false) {
            const status = document.getElementById('progress');
            status.textContent = message;
            status.className = 'status ' + (isError ? 'error' : 'success');
        }

        async function startReset() {
            if (!baseCodeHandle) {
                showStatus('Please select base code directory first', true);
                return;
            }

            if (!confirm('This will reset the version to 1.0.1. Are you sure?')) {
                return;
            }

            // Reset customer version display
            document.getElementById('customerVersion').textContent = 'Not Selected';

            // Show both buttons and instructions
            document.getElementById('selectCustomerBtn').style.display = 'block';
            document.getElementById('completeResetBtn').style.display = 'block';
            showStatus('Optional: Click "Step 2" to select customer code directory, or click "Complete Reset" to skip');
        }

        async function selectCustomerCodeAndReset() {
            try {
                // Let user select customer code directory
                customerCodeHandle = await window.showDirectoryPicker();
                
                // Try to read customer version
                try {
                    const versionFile = await customerCodeHandle.getFileHandle('version.py');
                    const file = await versionFile.getFile();
                    const text = await file.text();
                    const versionMatch = text.match(/return ["'](.+?)["']/);
                    if (versionMatch) {
                        document.getElementById('customerVersion').textContent = versionMatch[1];
                    } else {
                        document.getElementById('customerVersion').textContent = 'Invalid version format';
                    }
                } catch (err) {
                    document.getElementById('customerVersion').textContent = 'No version.py found';
                }
                
                showStatus('Customer code directory selected. Click "Complete Reset" to finish.');
            } catch (err) {
                document.getElementById('customerVersion').textContent = 'Not Selected';
                showStatus('Error selecting customer code: ' + err.message, true);
            }
        }

        async function completeReset() {
            try {
                // Reset version.py in base code directory
                const versionContent = `"""Version information."""\n\ndef get_version():\n    """Get the current version."""\n    return "1.0.1"\n\n__version__ = get_version()\n`;
                
                // Reset in base code directory
                const baseVersionHandle = await baseCodeHandle.getFileHandle('version.py', { create: true });
                const baseWritable = await baseVersionHandle.createWritable();
                await baseWritable.write(versionContent);
                await baseWritable.close();

                // Reset in customer code directory if selected
                if (customerCodeHandle) {
                    try {
                        const customerVersionHandle = await customerCodeHandle.getFileHandle('version.py', { create: true });
                        const customerWritable = await customerVersionHandle.createWritable();
                        await customerWritable.write(versionContent);
                        await customerWritable.close();
                        showStatus('Reset customer code version...');
                        document.getElementById('customerVersion').textContent = '1.0.1';
                    } catch (err) {
                        showStatus('Warning: Could not reset customer code: ' + err.message, true);
                    }
                } else {
                    document.getElementById('customerVersion').textContent = 'Not Selected';
                }

                // Reset GitHub version.json
                const versionInfo = {
                    version: "1.0.1",
                    changelog: "Version reset to 1.0.1",
                    files: []
                };

                // Push to GitHub
                showStatus('Resetting GitHub version...');
                await updateGitHubFile('version.json', JSON.stringify(versionInfo, null, 4), 'Reset version to 1.0.1');

                // Reset local version display
                currentVersion = '1.0.1';
                document.getElementById('currentVersion').textContent = currentVersion;
                document.getElementById('newVersion').value = '1.0.1';

                // Clear any selected files
                selectedFiles = [];
                document.getElementById('selectedFiles').innerHTML = '';
                
                // Update GitHub version display
                await checkGithubVersion();
                
                // Hide the buttons
                document.getElementById('selectCustomerBtn').style.display = 'none';
                document.getElementById('completeResetBtn').style.display = 'none';
                
                // Show completion message
                if (customerCodeHandle) {
                    showStatus('Version successfully reset to 1.0.1 in all locations');
                } else {
                    showStatus('Version successfully reset to 1.0.1 in base code and GitHub');
                }

                // Reset the customer code handle
                customerCodeHandle = null;
            } catch (err) {
                showStatus('Error resetting version: ' + err.message, true);
            }
        }

        async function checkGithubVersion() {
            try {
                document.getElementById('githubVersion').textContent = 'Checking...';
                const response = await fetch('https://api.github.com/repos/khanfar/khanfar-sys-updates/contents/version.json');
                if (response.ok) {
                    const data = await response.json();
                    const content = JSON.parse(atob(data.content));
                    document.getElementById('githubVersion').textContent = content.version;
                } else {
                    throw new Error('Failed to fetch GitHub version');
                }
            } catch (err) {
                document.getElementById('githubVersion').textContent = 'Error checking version';
            }
        }

        async function publishUpdate() {
            if (!baseCodeHandle || selectedFiles.length === 0) {
                showStatus('Please select base code directory and files first', true);
                return;
            }

            const version = document.getElementById('newVersion').value.trim();
            const changelog = document.getElementById('changelog').value.trim();

            if (!version || !changelog) {
                showStatus('Please enter version number and changelog', true);
                return;
            }

            enableUI(false);
            showStatus('Publishing update...');

            try {
                // Create updates directory if it doesn't exist
                const updatesHandle = await baseCodeHandle.getDirectoryHandle('updates', { create: true });

                // Process each file
                const processedFiles = [];
                for (const file of selectedFiles) {
                    showStatus(`Processing ${file.name}...`);
                    
                    const sourceFile = await file.handle.getFile();
                    const hash = await calculateHash(sourceFile);
                    
                    // Copy file to updates directory
                    const destHandle = await updatesHandle.getFileHandle(file.name, { create: true });
                    const writable = await destHandle.createWritable();
                    await writable.write(sourceFile);
                    await writable.close();

                    // Store file content for GitHub
                    const content = await sourceFile.text();
                    processedFiles.push({
                        path: file.path,
                        filename: file.name,
                        content: content,
                        hash: hash
                    });
                }

                // Create version.json
                const versionInfo = {
                    version: version,
                    changelog: changelog,
                    files: processedFiles.map(file => ({
                        path: file.path,
                        filename: file.filename,
                        hash: file.hash
                    }))
                };

                // Save version.json locally
                const versionHandle = await updatesHandle.getFileHandle('version.json', { create: true });
                const writable = await versionHandle.createWritable();
                await writable.write(JSON.stringify(versionInfo, null, 4));
                await writable.close();

                // Update version.py
                const versionContent = `"""Version information."""\n\ndef get_version():\n    """Get the current version."""\n    return "${version}"\n\n__version__ = get_version()\n`;
                
                const versionPyHandle = await baseCodeHandle.getFileHandle('version.py', { create: true });
                const versionWritable = await versionPyHandle.createWritable();
                await versionWritable.write(versionContent);
                await versionWritable.close();

                // Push to GitHub
                showStatus('Pushing to GitHub...');
                await updateGitHubFile('version.json', JSON.stringify(versionInfo, null, 4), `Update version.json to ${version}`);

                // Update each file on GitHub
                for (const file of processedFiles) {
                    showStatus(`Pushing ${file.filename} to GitHub...`);
                    await updateGitHubFile(file.filename, file.content, `Update ${file.filename} for version ${version}`);
                }

                showStatus('Update published successfully!');
                currentVersion = version;
                document.getElementById('currentVersion').textContent = currentVersion;
                
                // Refresh GitHub version
                await checkGithubVersion();
            } catch (err) {
                showStatus('Error publishing update: ' + err.message, true);
                console.error('Publishing error:', err);
            } finally {
                enableUI(true);
            }
        }

        async function listDirectoryContents(dirHandle, elementId) {
            const fileList = document.getElementById(elementId);
            fileList.innerHTML = '';
            
            try {
                for await (const entry of dirHandle.values()) {
                    const div = document.createElement('div');
                    div.className = 'file-item';
                    div.textContent = `${entry.kind === 'directory' ? '📁' : '📄'} ${entry.name}`;
                    fileList.appendChild(div);
                }
            } catch (err) {
                showStatus('Error listing directory contents: ' + err.message, true);
            }
        }

        // Initialize GitHub version check
        checkGithubVersion();
    </script>
</body>
</html>
