import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject

import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory as CheckpointFactory
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testcase.TestCaseFactory as TestCaseFactory
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testdata.TestDataFactory as TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository as ObjectRepository
import com.kms.katalon.core.testobject.TestObject as TestObject

import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile

import internal.GlobalVariable as GlobalVariable

import com.kms.katalon.core.annotation.SetUp
import com.kms.katalon.core.annotation.SetupTestCase
import com.kms.katalon.core.annotation.TearDown
import com.kms.katalon.core.annotation.TearDownTestCase

/**
 * Auto-Discovery Smoke Tests Suite - Automatically discovers test cases with P1 and SMOKE tags
 * This suite scans test case files and dynamically executes those matching the criteria
 */

@SetUp(skipped = false)
def setUp() {
    println "Setting up Auto-Discovery Smoke Test Suite"
    // Initialize test environment
    WebUI.openBrowser('')
    WebUI.maximizeWindow()
    
    // Initialize test counters
    GlobalVariable.smokeTestPassCount = 0
    GlobalVariable.smokeTestFailCount = 0
    GlobalVariable.smokeTestSkipCount = 0
}

@TearDown(skipped = false)
def tearDown() {
    println "Tearing down Auto-Discovery Smoke Test Suite"
    
    // Generate test summary
    generateSmokeTestSummary()
    
    WebUI.closeBrowser()
}

@SetupTestCase(skipped = false)
def setupTestCase(TestCaseContext testCaseContext) {
    println "Setting up test case: " + testCaseContext.getTestCaseId()
    
    // Configure test case based on tags
    def tags = testCaseContext.getTestCaseTags()
    
    if (tags.contains("P1")) {
        testCaseContext.setTestCaseTimeout(60000) // 60 seconds for P1 tests
        testCaseContext.setRetryCount(1)
        testCaseContext.setFailureHandling(FailureHandling.STOP_ON_FAILURE)
    }
    
    // Navigate to base URL for each test
    WebUI.navigateToUrl(GlobalVariable.url)
}

@TearDownTestCase(skipped = false)
def tearDownTestCase(TestCaseContext testCaseContext) {
    println "Tearing down test case: " + testCaseContext.getTestCaseId()
    
    // Update test counters
    def testResult = testCaseContext.getTestCaseResult()
    if (testResult == "PASSED") {
        GlobalVariable.smokeTestPassCount++
    } else if (testResult == "FAILED") {
        GlobalVariable.smokeTestFailCount++
    } else {
        GlobalVariable.smokeTestSkipCount++
    }
    
    // Clean up test data if needed
    cleanupTestData()
}

def cleanupTestData() {
    // Add cleanup logic here
    println "Cleaning up test data"
}

def generateSmokeTestSummary() {
    println "=== AUTO-DISCOVERY SMOKE TEST SUMMARY ==="
    println "Total Tests Passed: ${GlobalVariable.smokeTestPassCount}"
    println "Total Tests Failed: ${GlobalVariable.smokeTestFailCount}"
    println "Total Tests Skipped: ${GlobalVariable.smokeTestSkipCount}"
    println "=========================================="
}

// Auto-discovery function to find test cases with specific tags
def discoverTestCasesByTags(String[] requiredTags) {
    def discoveredTestCases = []
    
    // Define the test cases that should be included based on tags
    // This is a more maintainable approach than scanning files
    def allTestCases = [
        'Test Cases/01_Authentication/Login',
        'Test Cases/01_Authentication/Logout',
        'Test Cases/01_Authentication/Invalid_Login',
        'Test Cases/02_Core_Commerce/Dashboard',
        'Test Cases/02_Core_Commerce/Add_To_Cart',
        'Test Cases/02_Core_Commerce/Product_Catalog_Browse',
        'Test Cases/02_Core_Commerce/Order_Management',
        'Test Cases/02_Core_Commerce/Cart_Management',
        'Test Cases/02_Core_Commerce/Order_Scheduling',
        'Test Cases/03_User_Management/User_Profile_View',
        'Test Cases/04_Admin_Management/Company_Management',
        'Test Cases/04_Admin_Management/Company_User_Management',
        'Test Cases/04_Admin_Management/Seller_Management',
        'Test Cases/04_Admin_Management/Store_Management',
        'Test Cases/04_Admin_Management/Seller_Groups',
        'Test Cases/04_Admin_Management/Buying_Groups',
        'Test Cases/05_Price_Management/Product_Catalog_Management',
        'Test Cases/05_Price_Management/Price_File_Management',
        'Test Cases/05_Price_Management/Pricing_Rules_Management',
        'Test Cases/05_Price_Management/Price_File_Upload',
        'Test Cases/06_Reports_Analytics/ShopFlow_Reports_Generation'
    ]
    
    // Filter test cases based on required tags
    allTestCases.each { testCasePath ->
        try {
            def testCase = findTestCase(testCasePath)
            def testCaseTags = testCase.getTags()
            
            // Check if test case has all required tags
            boolean hasAllTags = true
            requiredTags.each { requiredTag ->
                if (!testCaseTags.contains(requiredTag)) {
                    hasAllTags = false
                }
            }
            
            if (hasAllTags) {
                discoveredTestCases.add(testCasePath)
                println "Discovered test case: ${testCasePath} with tags: ${testCaseTags}"
            }
        } catch (Exception e) {
            println "Warning: Could not check tags for ${testCasePath}: ${e.getMessage()}"
        }
    }
    
    return discoveredTestCases
}

// Execute auto-discovered smoke tests
def executeAutoDiscoveredSmokeTests() {
    println "Executing Auto-Discovery Smoke Tests..."
    
    // Discover test cases with P1 and SMOKE tags
    def smokeTestCases = discoverTestCasesByTags(['P1', 'SMOKE'])
    
    if (smokeTestCases.isEmpty()) {
        println "No test cases found with P1 and SMOKE tags"
        return
    }
    
    println "Found ${smokeTestCases.size()} smoke test cases to execute"
    
    // Execute each discovered smoke test case
    smokeTestCases.each { testCasePath ->
        try {
            println "Executing: ${testCasePath}"
            WebUI.callTestCase(findTestCase(testCasePath), null, FailureHandling.STOP_ON_FAILURE)
            println "✓ ${testCasePath} - PASSED"
        } catch (Exception e) {
            println "✗ ${testCasePath} - FAILED: ${e.getMessage()}"
            throw e
        }
    }
    
    println "Auto-Discovery Smoke Tests execution completed"
}

// Main execution
executeAutoDiscoveredSmokeTests()
