# Copyright (c) 2025 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import configparser
import os
import subprocess
import sys
import tempfile
from jinja2 import Environment, FileSystemLoader

def load_config(config_file):
    """Load configuration from file."""
    if not os.path.exists(config_file):
        raise FileNotFoundError(f"Configuration file not found: {config_file}")
    
    if not os.access(config_file, os.R_OK):
        raise PermissionError(f"Cannot read configuration file: {config_file}")
    
    config = {}
    
    # Simple key=value parser for shell-style config
    with open(config_file, 'r') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                if '=' in line:
                    key, value = line.split('=', 1)
                    key = key.strip()
                    value = value.strip().strip('"\'')
                    
                    # Handle command substitution like $(cat file)
                    if value.startswith('$(') and value.endswith(')'):
                        command = value[2:-1]
                        try:
                            result = subprocess.check_output(command, shell=True, text=True)
                            value = result.strip()
                        except subprocess.CalledProcessError as e:
                            raise RuntimeError(f"Failed to execute command '{command}': {e}")
                    
                    config[key] = value
    
    return config

def render_workflow_template(template_path, config):
    """Render workflow template with configuration."""
    if not os.path.exists(template_path):
        raise FileNotFoundError(f"Template file not found: {template_path}")
    
    # Read template content
    with open(template_path, 'r') as f:
        template_content = f.read()
    
    # Render with Jinja2
    env = Environment()
    template = env.from_string(template_content)
    
    # Process private key to add proper indentation for YAML
    if 'ssh_private_key_path' in config:
        try:
            with open(config['ssh_private_key_path'], 'r') as f:
                private_key_content = f.read().rstrip()
            # Add indentation for YAML multiline string
            config['ssh_private_key'] = '\n'.join([' ' * 10 + line for line in private_key_content.split('\n')])
        except Exception as e:
            raise RuntimeError(f"Failed to read SSH private key: {e}")
    
    return template.render(**config)

def upload_workflow(workflow_content):
    """Upload workflow to Mistral using openstack CLI."""
    try:
        # Create temporary file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
            f.write(workflow_content)
            temp_file = f.name
        
        try:
            # Upload using openstack CLI
            result = subprocess.run(
                ['openstack', 'workflow', 'create', temp_file],
                capture_output=True,
                text=True,
                check=True
            )
            print("Workflow uploaded successfully!")
            if result.stdout:
                print(result.stdout)
        finally:
            # Clean up temporary file
            os.unlink(temp_file)
            
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"Failed to upload workflow: {e.stderr}")
    except Exception as e:
        raise RuntimeError(f"Error during workflow upload: {e}")

def main():
    """Main entry point for workflow uploader."""
    config_file = '/etc/vmms/vmms-upload-workflow.conf'
    template_path = '/usr/share/vmms-common/workflows/migrate_vm_workflow.yaml.j2'
    
    try:
        # Load configuration
        print("Loading configuration...")
        config = load_config(config_file)
        
        # Render template
        print("Rendering workflow template...")
        workflow_content = render_workflow_template(template_path, config)
        
        # Upload workflow
        print("Uploading workflow to Mistral...")
        upload_workflow(workflow_content)
        
        print("Workflow upload completed successfully!")
        return 0
        
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1
