#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Setup Test Script
=================

This script tests the setup and configuration of the termination script.
Run this before using the main script to verify everything is configured correctly.
"""

import sys
import os
import codecs

# Set stdout to UTF-8 for Windows console support
if sys.platform == "win32":
    sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, 'strict')
    sys.stderr = codecs.getwriter("utf-8")(sys.stderr.buffer, 'strict')


def test_python_version():
    """Test Python version"""
    print("Testing Python version...")
    version = sys.version_info
    if version.major >= 3 and version.minor >= 8:
        print(f"  ✓ Python {version.major}.{version.minor}.{version.micro}")
        return True
    else:
        print(f"  ✗ Python {version.major}.{version.minor}.{version.micro} (requires 3.8+)")
        return False


def test_module_import(module_name):
    """Test if a module can be imported"""
    try:
        __import__(module_name)
        print(f"  ✓ {module_name}")
        return True
    except ImportError:
        print(f"  ✗ {module_name} (not installed)")
        return False


def test_file_exists(filepath, description):
    """Test if a file exists"""
    if os.path.exists(filepath):
        print(f"  ✓ {description}: {filepath}")
        return True
    else:
        print(f"  ✗ {description} not found: {filepath}")
        return False


def test_config_file():
    """Test config file"""
    print("\nTesting config file...")
    if not os.path.exists("config.json"):
        print("  ✗ config.json not found")
        return False

    try:
        import json
        with open("config.json", "r") as f:
            config = json.load(f)

        # Check required fields
        if "crm" in config and "url" in config["crm"]:
            print(f"  ✓ CRM URL: {config['crm']['url']}")
        else:
            print("  ✗ CRM URL not configured")

        if "crm" in config and "username" in config["crm"] and config["crm"]["username"]:
            print(f"  ✓ CRM Username: {config['crm']['username']}")
        else:
            print("  ⚠ CRM Username not configured (will prompt)")

        if "credentials" in config and "password_file" in config["credentials"]:
            password_file = config["credentials"]["password_file"]
            if os.path.exists(password_file):
                print(f"  ✓ Password file: {password_file}")
            else:
                print(f"  ⚠ Password file not found: {password_file}")

        return True

    except Exception as e:
        print(f"  ✗ Error reading config: {e}")
        return False


def test_ad_connection():
    """Test AD connection"""
    print("\nTesting AD connection...")

    try:
        from ad_query import query_ad_by_employee_id, ADQueryError

        # Try to query a test user (this will likely fail but tests the module)
        print("  Testing AD module...")
        try:
            # Try to connect to AD
            result = query_ad_by_employee_id("000000")  # Fake ID, will fail but tests connectivity
            print("  ⚠ AD query returned unexpected result")
        except ADQueryError as e:
            if "not found" in str(e).lower():
                print("  ✓ AD module working (user not found is expected)")
            else:
                print(f"  ⚠ AD connection issue: {e}")
        except Exception as e:
            print(f"  ✗ AD error: {e}")

        return True

    except ImportError:
        print("  ✗ Cannot import ad_query module")
        return False


def test_playwright():
    """Test Playwright installation"""
    print("\nTesting Playwright...")

    try:
        from playwright.sync_api import sync_playwright

        print("  ✓ Playwright Python package installed")

        # Test if browser is installed
        try:
            from playwright._impl._api_types import Error
            import subprocess

            # Try to get browser info
            result = subprocess.run(
                ["playwright", "show-browsers"],
                capture_output=True,
                text=True,
                timeout=10
            )

            if "chromium" in result.stdout.lower():
                print("  ✓ Playwright Chromium browser installed")
            else:
                print("  ⚠ Chromium browser may not be installed")
                print("    Run: playwright install chromium")

        except Exception as e:
            print(f"  ⚠ Cannot verify browser installation: {e}")
            print("    Run: playwright install chromium")

        return True

    except ImportError:
        print("  ✗ Playwright not installed")
        print("    Run: pip install playwright")
        return False


def main():
    """Run all tests"""
    print("="*60)
    print("SETUP TEST FOR BATCH TERMINATION SCRIPT")
    print("="*60)

    results = []

    # Test 1: Python version
    print("\n[1/6] Python Version")
    results.append(test_python_version())

    # Test 2: Required Python modules
    print("\n[2/6] Python Modules")
    modules = ["openpyxl", "requests", "playwright"]
    module_results = [test_module_import(m) for m in modules]
    results.extend(module_results)

    # Test 3: Custom modules
    print("\n[3/6] Custom Modules")
    custom_modules = ["dpapi_crypto", "ad_query", "crm_api", "playwright_login"]
    custom_results = [test_module_import(m) for m in custom_modules]
    results.extend(custom_results)

    # Test 4: Configuration files
    print("\n[4/6] Configuration Files")
    results.append(test_config_file())
    results.append(test_file_exists("Save-EncryptedPassword.ps1", "Password encryption script"))

    # Test 5: AD connection
    print("\n[5/6] Active Directory")
    test_ad_connection()

    # Test 6: Playwright
    print("\n[6/6] Playwright")
    test_playwright()

    # Summary
    print("\n" + "="*60)
    print("SUMMARY")
    print("="*60)

    passed = sum(1 for r in results if r)
    total = len(results)

    if passed == total:
        print(f"✓ All tests passed ({passed}/{total})")
        print("\nSetup is complete! You can now run the termination script.")
        print("\nNext steps:")
        print("  1. Ensure config.json is configured with your CRM credentials")
        print("  2. Run: python terminate_users.py --what-if --excel AdTermination.xlsx")
        return 0
    else:
        print(f"✗ Some tests failed ({passed}/{total})")
        print("\nPlease fix the issues above before running the termination script.")
        return 1


if __name__ == "__main__":
    sys.exit(main())
