import os
import sys

def check_path(path, description, context_dir="."):
    # Cleanup path string
    path = path.strip().strip('"').strip("'")
    
    # Ignore internal docker volumes or absolute paths that might be inside container
    if not path.startswith("./") and not path.startswith("/") and not path.startswith(".."):
        # Assume named volume or config setting
        return True

    # Split host:container mapping
    host_path_raw = path.split(":")[0]
    
    # Resolve relative paths relative to CWD
    if host_path_raw.startswith("./"):
        host_path = os.path.join(os.getcwd(), host_path_raw[2:])
    elif host_path_raw.startswith("../"):
        host_path = os.path.abspath(host_path_raw)
    else:
        host_path = host_path_raw

    if os.path.exists(host_path):
        print(f"✅ FOUND: {description} -> {host_path_raw}")
        return True
    else:
        print(f"❌ MISSING: {description} -> {host_path_raw}")
        return False

def validate_compose_text():
    print("--- 🚀 Starting Pre-Flight Check (Text-Based) ---")
    
    if not os.path.exists("docker-compose.yml"):
        print("❌ CRITICAL: docker-compose.yml not found!")
        return

    with open("docker-compose.yml", "r") as f:
        lines = f.readlines()

    current_service = "Unknown"
    all_valid = True
    in_volumes = False
    
    for line in lines:
        line = line.rstrip()
        clean_line = line.strip()
        
        # Detect Service Block (heuristic)
        if line.startswith("  ") and not line.startswith("    ") and ":" in line and not clean_line.startswith("#"):
            current_service = clean_line.replace(":", "")
            print(f"\nScanning Service: [{current_service}]")
            in_volumes = False
            continue

        # Check Context
        if "context:" in clean_line:
            path = clean_line.split("context:")[1].strip()
            if not check_path(path, f"Build Context ({current_service})"):
                all_valid = False

        # Check Env File
        if clean_line.startswith("- .env"):
             if not check_path(".env", f"Env File ({current_service})"):
                all_valid = False

        # Check Volumes Block Start
        if clean_line.startswith("volumes:"):
            in_volumes = True
            continue
            
        # Check Volume Entries
        if in_volumes and clean_line.startswith("-") and ":" in clean_line:
            # Simple heuristic to stop reading volumes if indentation changes or new block starts
            if not line.startswith("      -"):
                 in_volumes = False
            else:
                vol_path = clean_line[1:].strip() # Remove dash
                if not check_path(vol_path, f"Volume ({current_service})"):
                    all_valid = False

    print("\n--- 🏁 Result ---")
    if all_valid:
        print("✅ READY FOR TAKEOFF: All referenced files and directories exist.")
    else:
        print("❌ ABORT: Missing files detected. Migration would fail.")

if __name__ == "__main__":
    validate_compose_text()