import unittest
import os
import sys

class TestRunner:
    def __init__(self, test_directory="tests"):
        self.test_directory = test_directory

    def run_tests(self):
        """
        Discovers and runs all tests in the specified directory.
        """
        suite = unittest.TestLoader().discover(self.test_directory, pattern="test*.py")
        runner = unittest.TextTestRunner(verbosity=2)
        result = runner.run(suite)

        return result

    def run_specific_test(self, module_name, class_name, method_name):
       """
       Runs a specific test method in a test case.
       """
       try:
           module = __import__(module_name, fromlist=[class_name])
           test_class = getattr(module, class_name)
           test_method = test_class(method_name)
           suite = unittest.TestSuite()
           suite.addTest(test_method)
           runner = unittest.TextTestRunner(verbosity=2)
           result = runner.run(suite)
           return result

       except ImportError as e:
           print(f"Error importing module {module_name}: {e}")
           return None
       except AttributeError as e:
           print(f"Error finding class or method: {e}")
           return None
       except Exception as e:
           print(f"An unexpected error occurred: {e}")
           return None


if __name__ == '__main__':
    # Example Usage
    runner = TestRunner("generated_tests")  # Assuming tests are in 'generated_tests' directory
    result = runner.run_tests()

    # Example to run a specific test
    # Assuming you have a test file generated_tests/test_example_story.py
    # and a test class TestExampleStory
    # and a test method test_example_story_0
    # runner.run_specific_test("generated_tests.test_example_story", "TestExampleStory", "test_example_story_0")

    if result.failures or result.errors:
        sys.exit(1) # Exit with an error code if tests fail