import subprocess
import tempfile


def show_vscode_diff_and_get_changes(original_content, proposed_modified_content, original_title="Original", modified_title="Proposed Changes"):
    """
    Displays a diff between two strings in VS Code's native diff UI,
    allows user to make changes, and returns the final modified content.

    Args:
        original_content (str): The content representing the 'before' state.
        proposed_modified_content (str): The content representing the 'after' state,
                                         which the user can edit.
        original_title (str): An optional title for the original file in the diff view.
        modified_title (str): An optional title for the modified file in the diff view.

    Returns:
        str: The content of the modified file after the user has closed the VS Code diff window.
             Returns None if an error occurs or the diff window is not opened.
    """
    final_modified_content = None

    # Create temporary files for the original and modified content
    # Using NamedTemporaryFile ensures a visible path and automatic cleanup
    # 'w+' mode allows writing and reading text
    with tempfile.NamedTemporaryFile(mode='w+', delete=True, suffix='.txt', encoding='utf-8') as original_file:
        original_file.write(original_content)
        original_file.flush() # Ensure all content is written to disk
        original_file_path = original_file.name

        # The second file passed to --diff is the editable one.
        with tempfile.NamedTemporaryFile(mode='w+', delete=True, suffix='.txt', encoding='utf-8') as modified_file:
            modified_file.write(proposed_modified_content)
            modified_file.flush() # Ensure all content is written to disk
            modified_file_path = modified_file.name

            print(f"Opening diff in VS Code: '{original_title}' vs '{modified_title}'")
            print(f"Original file path: {original_file_path}")
            print(f"Modified file path: {modified_file_path}")
            print("Please make any desired changes in the right pane of the VS Code diff window and then close it.")

            try:
                # Construct the VS Code command.
                # --diff opens the diff editor.
                # --wait makes the Python script pause until the VS Code window is closed.
                # The second file (modified_file_path) will be editable.
                vscode_command = ["code", "--diff", original_file_path, modified_file_path, "--wait"]

                # Execute the command. check=True will raise an exception for non-zero exit codes.
                subprocess.run(vscode_command, check=True)
                print("VS Code diff window closed. Reading final content...")

                # After the VS Code window is closed, read the content from the modified file
                # Seek to the beginning of the file before reading
                modified_file.seek(0)
                final_modified_content = modified_file.read()
                print("Successfully read modified content from VS Code.")

            except FileNotFoundError:
                print("Error: 'code' command not found. Make sure VS Code is installed and added to your system's PATH.")
                print("On macOS, you might need to run 'Shell Command: Install 'code' command in PATH' from VS Code's Command Palette.")
            except subprocess.CalledProcessError as e:
                print(f"Error executing VS Code command: {e}")
            except Exception as e:
                print(f"An unexpected error occurred: {e}")

    return final_modified_content

# --- Example Usage ---
if __name__ == "__main__":
    # Simulate content generated by your tool
    before_text = """
    This is the first line.
    This is the second line.
    This line is changed.
    This is the fourth line.
    A line to be removed.
    """

    after_text_proposed = """
    This is the first line.
    This is the second line, but modified slightly.
    This line has been changed.
    This is the fourth line.
    This is a newly added line.
    """

    # Call the function to show the diff and get user's changes
    user_approved_content = show_vscode_diff_and_get_changes(
        before_text,
        after_text_proposed,
        original_title="Original Script",
        modified_title="Proposed Changes (Editable)"
    )

    if user_approved_content is not None:
        print("\n--- User's Final Approved Content ---")
        print(user_approved_content)
        # You can now use 'user_approved_content' in your Python script
        # For example, save it to a permanent file, process it further, etc.
    else:
        print("\nNo content was returned from the VS Code diff session.")

    print("\nScript finished executing.")
