#!/usr/bin/env python3
"""
Dynamic inventory script for Ansible that reads OpenTofu state
to get VM details and infrastructure config automatically.

Usage:
    ansible-playbook -i inventory.py deploy.yaml

The script reads `tofu output -json` from the sibling opentofu/ directory
and constructs an Ansible inventory with all outputs as host variables.
"""

import json
import subprocess
import sys
import os


def get_tofu_output():
    """Get OpenTofu output values."""
    try:
        tofu_dir = os.path.join(os.path.dirname(__file__), '..', 'opentofu')
        result = subprocess.run(
            ['tofu', 'output', '-json'],
            cwd=tofu_dir,
            capture_output=True,
            text=True,
            check=True
        )
        return json.loads(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"Error getting OpenTofu output: {e}", file=sys.stderr)
        return None
    except json.JSONDecodeError as e:
        print(f"Error parsing OpenTofu output: {e}", file=sys.stderr)
        return None


def main():
    """Generate Ansible inventory from OpenTofu state."""
    # Replace '{{ app_name }}' with the actual app name and group name
    group_name = "{{ app_name }}_server"

    tofu_output = get_tofu_output()

    if not tofu_output:
        print(json.dumps({
            "_meta": {"hostvars": {}},
            "all": {"hosts": []},
            group_name: {"hosts": []}
        }))
        return

    # Extract all outputs into host variables
    public_ip = tofu_output.get('ec2_public_ip', {}).get('value')
    hostvars = {}

    if public_ip:
        # Map all tofu outputs to Ansible variables
        for key, output in tofu_output.items():
            hostvars[key] = output.get('value')

        # Add SSH connection details
        hostvars.update({
            "ansible_user": "ubuntu",
            "ansible_ssh_private_key_file": "~/.ssh/gemma-infra.pem",
            "public_ip": public_ip,
        })

    inventory = {
        "_meta": {
            "hostvars": {public_ip: hostvars} if public_ip else {}
        },
        "all": {
            "hosts": [public_ip] if public_ip else []
        },
        group_name: {
            "hosts": [public_ip] if public_ip else []
        }
    }

    print(json.dumps(inventory, indent=2))


if __name__ == "__main__":
    main()
