"""
ContainerLab deploy logic: resolve stage topology path and run containerlab deploy.

Uses the process environment (no custom env). By default containerlab creates the
lab directory next to the topology file, so with topology at stage_dir/clab/topology.clab.yaml
the lab (e.g. clab-topology-small_Tier) ends up in stage_dir/clab/ as desired.
"""

import logging
import subprocess
from pathlib import Path

logger = logging.getLogger(__name__)


def get_stage_topology_path(stage_dir: str | Path) -> Path:
    """Return the stage topology file path (same as used by preprocess / containerlab inspect)."""
    return Path(stage_dir) / "clab" / "topology.clab.yaml"


def run_deploy_clab(stage_dir: str | Path) -> None:
    """Run containerlab deploy with the stage topology file."""
    topology_path = get_stage_topology_path(stage_dir)
    if not topology_path.exists():
        print(f"Topology file not found: {topology_path}")
        return
    cmd = ["containerlab", "deploy", "-t", str(topology_path)]
    print(f"Running: {' '.join(cmd)}")
    result = subprocess.run(cmd)
    if result.returncode != 0:
        print(f"containerlab deploy exited with code {result.returncode}")
        return
    subprocess.run(["iptables", "-F"], check=False)
    subprocess.run(["iptables", "-F", "-t", "nat"], check=False)


def run_inspect_clab(stage_dir: str | Path) -> None:
    """Run containerlab inspect with the stage topology."""
    topology_path = get_stage_topology_path(stage_dir)
    if not topology_path.exists():
        print(f"Topology file not found: {topology_path}")
        return
    cmd = ["containerlab", "inspect", "-t", str(topology_path)]
    print(f"Running: {' '.join(cmd)}")
    result = subprocess.run(cmd)
    if result.returncode != 0:
        print(f"containerlab inspect exited with code {result.returncode}")


def run_destroy_clab(stage_dir: str | Path) -> bool:
    """Run containerlab destroy with the stage topology.

    Uses --graceful so containers disconnect from the management network before
    removal. If destroy fails (e.g. 'network has active endpoints'), retries
    once after a short delay.

    Returns True if destroy succeeded, False otherwise.
    """
    print(f"Running containerlab destroy with stage directory: {stage_dir}")
    topology_path = get_stage_topology_path(stage_dir)
    if not topology_path.exists():
        print(f"Topology file not found: {topology_path}")
        return False
    cmd = ["containerlab", "destroy", "-t", str(topology_path)]
    print(f"Running: {' '.join(cmd)}")
    try:
        result = subprocess.run(cmd)
    except Exception as e:
        logger.warning(f"Error running containerlab destroy: {e}")
        return False
    if result.returncode == 0:
        return True
    logger.warning(f"containerlab destroy exited with code {result.returncode}")
    return False
