import os
import shutil
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from swai_inst import installer, utils

def setup_test_files():
    base_dir = os.path.abspath('icon_test_env')
    os.makedirs(base_dir, exist_ok=True)
    
    # Create test icons
    icon_paths = {
        "same": os.path.join(base_dir, "icon_same.png"),
        "inside": os.path.join(base_dir, "icons", "icon_inside.png"),
        "outside": os.path.join(os.path.dirname(base_dir), "icon_outside.png"),
        "full": os.path.join(base_dir, "icon_full.png"),
        "tilde": os.path.expanduser("~/icon_tilde.png"),
    }
    
    for key, path in icon_paths.items():
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, 'w') as f:
            f.write("mock png content")
            
    # Create swai files in base_dir
    swai_files = {
        "same": {
            "app_name": "Test Same",
            "app_id": "com.test.same",
            "icon_url": "icon_same.png",
            "categories": ["Utility"]
        },
        "inside": {
            "app_name": "Test Inside",
            "app_id": "com.test.inside",
            "icon_url": "icons/icon_inside.png",
            "categories": ["Utility"]
        },
        "outside": {
            "app_name": "Test Outside",
            "app_id": "com.test.outside",
            "icon_url": "../icon_outside.png",
            "categories": ["Utility"]
        },
        "full": {
            "app_name": "Test Full",
            "app_id": "com.test.full",
            "icon_url": icon_paths["full"],
            "categories": ["Utility"]
        },
        "tilde": {
            "app_name": "Test Tilde",
            "app_id": "com.test.tilde",
            "icon_url": "~/icon_tilde.png",
            "categories": ["Utility"]
        }
    }
    
    swai_paths = {}
    for key, data in swai_files.items():
        swai_path = os.path.join(base_dir, f"{key}.swai")
        with open(swai_path, 'w') as f:
            f.write(f"app_name: {data['app_name']}\n")
            f.write(f"app_id: {data['app_id']}\n")
            f.write(f"icon_url: {data['icon_url']}\n")
            f.write("categories:\n  - Utility\n")
        swai_paths[key] = swai_path
        
    return base_dir, swai_paths, icon_paths

def test():
    base_dir, swai_paths, icon_paths = setup_test_files()
    
    is_local = os.getuid() != 0
    swai_dir, desktop_dir, icon_base_dir = utils.get_install_paths(local_install=is_local)
    
    print(f"Testing {'local' if is_local else 'system-wide'} icon installation...")
    for key, swai_path in swai_paths.items():
        print(f"\n--- Testing '{key}' condition ---")
        try:
            app_name, app_id = installer.install_from_file(swai_path, local_install=is_local, verbose=True)
            expected_icon = os.path.join(icon_base_dir, f"io.stillhq.swai.{app_id}.png")
            if os.path.exists(expected_icon):
                print(f"[SUCCESS] Icon found at {expected_icon}")
            else:
                print(f"[FAILED] Icon NOT found at {expected_icon}")
            
            # Clean up installation
            installer.remove_from_app_id(app_id, local_install=is_local, verbose=False)
        except Exception as e:
            print(f"[ERROR] Installation failed for {key}: {e}")

if __name__ == "__main__":
    test()
