"""
Test script for ExportMailer functionality.

This script tests the Phase 3 implementation of the ExportMailer feature.
"""

import os
import sys
from features.export_mailer import run_export_only, run_export_mailer
from core.logger import get_hotellabexport_logger


def test_export_only():
    """Test the export functionality without email sending."""
    print("Testing ExportMailer export functionality...")

    try:
        success, main_csv, blocks_csv = run_export_only()

        if success:
            print(f"✓ Export successful!")
            print(f"  Main CSV: {main_csv}")
            print(f"  Blocks CSV: {blocks_csv}")

            # Check if files exist
            if main_csv and os.path.exists(main_csv):
                print(f"✓ Main CSV file exists: {main_csv}")
                with open(main_csv, "r", encoding="cp1251") as f:
                    lines = f.readlines()
                    print(f"  Main CSV contains {len(lines)} lines")
            else:
                print(f"✗ Main CSV file not found: {main_csv}")

            if blocks_csv and os.path.exists(blocks_csv):
                print(f"✓ Blocks CSV file exists: {blocks_csv}")
                with open(blocks_csv, "r", encoding="cp1251") as f:
                    lines = f.readlines()
                    print(f"  Blocks CSV contains {len(lines)} lines")
            else:
                print(f"✗ Blocks CSV file not found: {blocks_csv}")

        else:
            print("✗ Export failed")

    except Exception as e:
        print(f"✗ Export test failed with exception: {str(e)}")


def test_full_export_mailer():
    """Test the complete ExportMailer functionality including email."""
    print("\nTesting complete ExportMailer functionality (including email)...")

    try:
        success = run_export_mailer()

        if success:
            print("✓ Complete ExportMailer process successful!")
        else:
            print("✗ Complete ExportMailer process failed")

    except Exception as e:
        print(f"✗ Complete ExportMailer test failed with exception: {str(e)}")


def check_configuration():
    """Check if configuration is properly set up."""
    print("Checking configuration...")

    from core.config import get_config

    config = get_config()

    required_keys = [
        "hotel_key",
        "url",
        "block-url",
        "sendfrom",
        "sendto",
        "mailserver",
        "port",
        "pwd",
        "ssl",
        "oracleconnectstring",
        "nls_lang",
        "file_encoding",
    ]

    missing_keys = []
    for key in required_keys:
        value = config.get(key)
        if not value:
            missing_keys.append(key)
        else:
            print(f"  {key}: {'*' * len(value) if 'pwd' in key else value}")

    if missing_keys:
        print(f"✗ Missing configuration keys: {', '.join(missing_keys)}")
        return False
    else:
        print("✓ All required configuration keys present")
        return True


def main():
    """Main test function."""
    print("=== ExportMailer Phase 3 Test ===\n")

    # Check configuration
    config_ok = check_configuration()

    if not config_ok:
        print("\n✗ Configuration incomplete. Please update settings.ini")
        return

    # Test export only (safer for testing)
    test_export_only()

    # Ask user if they want to test email functionality
    response = (
        input("\nDo you want to test email functionality? (y/N): ").strip().lower()
    )
    if response in ["y", "yes"]:
        test_full_export_mailer()
    else:
        print("Skipping email test.")

    print("\n=== Test Complete ===")

    # Show log file location
    log_file = "log/hotellabexport.log"
    if os.path.exists(log_file):
        print(f"\nCheck the log file for details: {log_file}")


if __name__ == "__main__":
    main()
