"""
textfsmgen.core.testing
=======================

Utilities for testing pattern resolution and keyword mappings.
"""

import re
import tempfile
from pathlib import Path, PurePath
from datetime import datetime

from textfsmgen.libs import shell
from textfsmgen.libs import text
from textfsmgen.libs.generic import StatusString


def get_temp_dir():
    """Return a temporary directory path"""
    return tempfile.gettempdir()


def create_temp_python_file(prefix="test_pytest_", content=""):
    """Create a temporary Python file with optional content and return its path."""
    temp = tempfile.NamedTemporaryFile(
        delete=False,
        prefix=prefix,
        suffix=".py",
        mode="w",
        encoding="utf-8",
    )
    if content:
        temp.write(content)
    temp_path = Path(temp.name)
    temp.close()  # allow pytest to open it
    return temp_path


def validate_python_executable(python_path):
    """Return a StatusString indicating whether the Python executable is valid."""
    result = shell.execute_command(f"{python_path} --version")
    return StatusString(result.output, result.is_success)


def validate_python_package(python_path, pkg):
    """Return a StatusString indicating whether a Python package is installed."""
    result = shell.execute_command(f"{python_path} -m pip show {pkg}")
    return StatusString(result.output, result.is_success)


def validate_requirement(python_path):
    """Return a Status indicating whether a Python package is installed."""
    footer = text.dedent_and_strip("""
        ==============================
        How to Set Up a Python Virtual Environment and Install TextFSMGen and Pytest
        ==============================
    
        1. Create a virtual environment
           • python -m venv {venv_path}
    
        2. Activate the virtual environment
           • Windows (PowerShell):     ./{venv_path}/Scripts/activate.ps1
           • Windows (Command Prompt): ./{venv_path}/Scripts/activate.bat
           • Linux/macOS (bash/zsh):   source ./{venv_path}/bin/activate
           • Linux (csh/tcsh):         source ./{venv_path}/bin/activate.csh
    
        3. Install TextFSMGen and Pytest
           • python -m pip install textfsmgen
           • python -m pip install pytest
    
        ==============================
        Python Executable Inside the Virtual Environment
        ==============================
        • Windows: ./{venv_path}/Scripts/python.exe
        • Linux/macOS: ./{venv_path}/bin/python
    """)

    ok = validate_python_executable(python_path)
    if not ok:
        msg = f"{ok}\n\n\n{footer}"
        return StatusString(msg, False)

    for pkg in ["textfsmgen", "pytest"]:
        ok = validate_python_package(python_path, pkg)
        if not ok:
            msg = f"{ok}\n\n\n{footer}"
            return StatusString(msg, False)

    return StatusString("", True)


def build_test_summary(temp_file, command):
    """Return a formatted summary of the test run."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    deleted = "No" if temp_file.exists() else 'Yes'
    summary = text.dedent_and_strip(f"""
        +-----------------------------------------------------------------------
        | Summary
        +-----------------------------------------------------------------------
        | Created Date/Time: {timestamp}
        | Temp File Path   : {temp_file}
        | Deleted After Run: {deleted}
        +-----------------------------------------------------------------------
        | Command Executed : {command}
        +-----------------------------------------------------------------------
    """)
    return summary


def execute_test_script(python_path, content="", deleted=True):
    """Run a generated test script and return a StatusString summary."""
    ok = validate_requirement(python_path)
    if not ok:
        return ok

    pattern = '(?i)"""Python (?P<test_type>[a-z]+) script is generated by TextFSMGen CE"""'
    match = re.match(pattern, content)
    if not match:
        return StatusString("Invalid test script generated by TextFSMGen", False)

    test_type = match.group("test_type").lower().replace("snippet", "python")
    temp_file = create_temp_python_file(prefix=f"test_{test_type}_", content=content)

    command = f"{python_path} {temp_file}"

    result = shell.execute_command(command)
    if deleted:
        temp_file.unlink(missing_ok=True)
    summary = build_test_summary(temp_file, command)
    return StatusString(f"{summary}\n\n\n{result.output}", result.is_success)
