# Copyright 2025 Foundry Technologies, Inc.
#
# 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.

"""SSH connectivity for FCP instances."""

import subprocess
import sys
from typing import Optional

from .errors import SSHError


def ssh_to_instance(ip: str, user: str = "ubuntu", ssh_key: Optional[str] = None):
    """Establish interactive SSH session.
    
    Args:
        ip: Instance public IP address
        user: SSH username (default: ubuntu)
        ssh_key: Path to private key file
    
    Raises:
        SSHError: Connection failure
    """
    if not ip:
        raise SSHError("No IP address available for instance")
    
    ssh_args = ["ssh"]
    
    # Configure identity file
    if ssh_key:
        ssh_args.extend(["-i", ssh_key])
    
    # Bypass host key verification for ephemeral instances
    ssh_args.extend([
        "-o", "StrictHostKeyChecking=no",
        "-o", "UserKnownHostsFile=/dev/null",
        "-o", "ConnectTimeout=10",
        f"{user}@{ip}"
    ])
    
    # Execute interactive SSH session
    try:
        subprocess.run(ssh_args, check=False)
    except KeyboardInterrupt:
        # Handle interrupt gracefully
        sys.exit(0)
    except Exception as e:
        raise SSHError(f"SSH connection failed: {e}")