# MCP Server Demo Test Script
# Tests the complete AI + Human collaboration workflow

param(
    [string]$BaseUrl = "http://localhost:5000",
    [string]$Username = "mcp_demo_user",
    [string]$Email = "mcp.demo@colaflow.dev",
    [string]$Password = "Demo@123456"
)

# Global variables
$ApiKey = ""
$JwtToken = ""
$ProjectId = ""
$PendingChangeId = ""
$EpicId = ""

# Helper function for API calls
function Invoke-Api {
    param(
        [string]$Method,
        [string]$Endpoint,
        [object]$Body = $null,
        [hashtable]$Headers = @{},
        [switch]$UseMcpAuth
    )

    $url = "$BaseUrl$Endpoint"

    if ($UseMcpAuth -and $ApiKey) {
        $Headers["X-MCP-API-Key"] = $ApiKey
    } elseif ($JwtToken) {
        $Headers["Authorization"] = "Bearer $JwtToken"
    }

    $Headers["Content-Type"] = "application/json"

    try {
        if ($Body) {
            $jsonBody = $Body | ConvertTo-Json -Depth 10
            $response = Invoke-RestMethod -Uri $url -Method $Method -Headers $Headers -Body $jsonBody -ErrorAction Stop
        } else {
            $response = Invoke-RestMethod -Uri $url -Method $Method -Headers $Headers -ErrorAction Stop
        }
        return $response
    } catch {
        Write-Host "Error calling $Method $Endpoint" -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Red
        if ($_.ErrorDetails) {
            Write-Host $_.ErrorDetails.Message -ForegroundColor Red
        }
        throw
    }
}

# Main test flow
Write-Host "=== MCP Server Demo Test ===" -ForegroundColor Cyan
Write-Host "Base URL: $BaseUrl" -ForegroundColor Gray
Write-Host "Username: $Username" -ForegroundColor Gray
Write-Host ""

# Step 0: Check if services are running
Write-Host "[Step 0] Checking if services are running..." -ForegroundColor Yellow
try {
    $healthCheck = Invoke-RestMethod -Uri "$BaseUrl/api/health" -Method Get -ErrorAction Stop
    Write-Host "✓ API is running" -ForegroundColor Green
    Write-Host "  Status: $($healthCheck.status)" -ForegroundColor Gray
} catch {
    Write-Host "✗ API is not running at $BaseUrl" -ForegroundColor Red
    Write-Host "  Please start the API with: dotnet run --project src/ColaFlow.Api" -ForegroundColor Yellow
    exit 1
}

# Step 1: Register user (if not exists) and login
Write-Host "`n[Step 1] Register and login..." -ForegroundColor Yellow
try {
    # Try to register
    $registerBody = @{
        username = $Username
        email = $Email
        password = $Password
    }

    try {
        $registerResponse = Invoke-Api -Method Post -Endpoint "/api/auth/register" -Body $registerBody
        Write-Host "✓ User registered successfully" -ForegroundColor Green
    } catch {
        Write-Host "  User may already exist, proceeding to login..." -ForegroundColor Gray
    }

    # Login
    $loginBody = @{
        email = $Email
        password = $Password
    }

    $loginResponse = Invoke-Api -Method Post -Endpoint "/api/auth/login" -Body $loginBody
    $JwtToken = $loginResponse.token
    Write-Host "✓ Login successful" -ForegroundColor Green
    Write-Host "  JWT Token: $($JwtToken.Substring(0, 50))..." -ForegroundColor Gray
} catch {
    Write-Host "✗ Failed to login" -ForegroundColor Red
    exit 1
}

# Step 2: Create Test Project
Write-Host "`n[Step 2] Create Test Project..." -ForegroundColor Yellow
try {
    $projectBody = @{
        name = "MCP Demo Project $(Get-Date -Format 'yyyyMMdd_HHmmss')"
        key = "MCP$(Get-Date -Format 'HHmmss')"
        description = "Test project for MCP Server demo"
    }

    $projectResponse = Invoke-Api -Method Post -Endpoint "/api/projects" -Body $projectBody
    $ProjectId = $projectResponse.id
    Write-Host "✓ Project created successfully" -ForegroundColor Green
    Write-Host "  Project ID: $ProjectId" -ForegroundColor Gray
    Write-Host "  Project Name: $($projectResponse.name)" -ForegroundColor Gray
    Write-Host "  Project Key: $($projectResponse.key)" -ForegroundColor Gray
} catch {
    Write-Host "✗ Failed to create project" -ForegroundColor Red
    exit 1
}

# Step 3: Create MCP API Key
Write-Host "`n[Step 3] Create MCP API Key..." -ForegroundColor Yellow
try {
    $apiKeyBody = @{
        name = "Demo API Key $(Get-Date -Format 'HHmmss')"
        permissions = @("read", "write")
    }

    $apiKeyResponse = Invoke-Api -Method Post -Endpoint "/api/mcp/api-keys" -Body $apiKeyBody
    $ApiKey = $apiKeyResponse.key
    Write-Host "✓ MCP API Key created successfully" -ForegroundColor Green
    Write-Host "  API Key: $($ApiKey.Substring(0, 50))..." -ForegroundColor Gray
    Write-Host "  Key ID: $($apiKeyResponse.id)" -ForegroundColor Gray
    Write-Host "  Permissions: $($apiKeyResponse.permissions -join ', ')" -ForegroundColor Gray
} catch {
    Write-Host "✗ Failed to create MCP API Key" -ForegroundColor Red
    exit 1
}

# Step 4: Test MCP Resources (list)
Write-Host "`n[Step 4] Test MCP Resources (list)..." -ForegroundColor Yellow
try {
    $resourcesResponse = Invoke-Api -Method Get -Endpoint "/api/mcp/resources" -UseMcpAuth
    Write-Host "✓ Resources list retrieved successfully" -ForegroundColor Green
    Write-Host "  Total resources: $($resourcesResponse.resources.Count)" -ForegroundColor Gray
    foreach ($resource in $resourcesResponse.resources) {
        Write-Host "    - $($resource.uri): $($resource.name)" -ForegroundColor Gray
    }
} catch {
    Write-Host "✗ Failed to get resources list" -ForegroundColor Red
    exit 1
}

# Step 5: Test MCP Resources (read project)
Write-Host "`n[Step 5] Test MCP Resources (read project)..." -ForegroundColor Yellow
try {
    $projectUri = "project://$ProjectId"
    $resourceReadResponse = Invoke-Api -Method Get -Endpoint "/api/mcp/resources/read?uri=$([System.Web.HttpUtility]::UrlEncode($projectUri))" -UseMcpAuth
    Write-Host "✓ Project resource read successfully" -ForegroundColor Green
    Write-Host "  URI: $($resourceReadResponse.uri)" -ForegroundColor Gray
    Write-Host "  MIME Type: $($resourceReadResponse.mimeType)" -ForegroundColor Gray
    if ($resourceReadResponse.contents -and $resourceReadResponse.contents.Count -gt 0) {
        $content = $resourceReadResponse.contents[0]
        Write-Host "  Content (first 200 chars):" -ForegroundColor Gray
        $contentPreview = $content.text.Substring(0, [Math]::Min(200, $content.text.Length))
        Write-Host "    $contentPreview..." -ForegroundColor Gray
    }
} catch {
    Write-Host "✗ Failed to read project resource" -ForegroundColor Red
    exit 1
}

# Step 6: Test MCP Tools (create_epic via Tool)
Write-Host "`n[Step 6] AI proposes creating Epic (via MCP Tool)..." -ForegroundColor Yellow
try {
    $createEpicToolBody = @{
        name = "tools/create_epic"
        arguments = @{
            projectId = $ProjectId
            title = "MCP Demo Epic - User Authentication System"
            description = "Implement complete user authentication system with SSO, MFA, and role-based access control"
            priority = "High"
        }
    }

    $toolResponse = Invoke-Api -Method Post -Endpoint "/api/mcp/tools/call" -Body $createEpicToolBody -UseMcpAuth
    Write-Host "✓ MCP Tool call successful (PendingChange created)" -ForegroundColor Green
    Write-Host "  Tool: $($toolResponse.name)" -ForegroundColor Gray

    if ($toolResponse.content -and $toolResponse.content.Count -gt 0) {
        $resultContent = $toolResponse.content[0]
        if ($resultContent.type -eq "text") {
            Write-Host "  Result:" -ForegroundColor Gray
            Write-Host "    $($resultContent.text)" -ForegroundColor Gray

            # Extract PendingChangeId from result text
            if ($resultContent.text -match "PendingChange ID: ([a-f0-9\-]+)") {
                $PendingChangeId = $matches[1]
                Write-Host "  Pending Change ID: $PendingChangeId" -ForegroundColor Cyan
            }
        }
    }
} catch {
    Write-Host "✗ Failed to call MCP tool" -ForegroundColor Red
    exit 1
}

# Step 7: Get PendingChange details
Write-Host "`n[Step 7] Get PendingChange details..." -ForegroundColor Yellow
try {
    $pendingChangeResponse = Invoke-Api -Method Get -Endpoint "/api/mcp/pending-changes/$PendingChangeId"
    Write-Host "✓ PendingChange retrieved successfully" -ForegroundColor Green
    Write-Host "  Change ID: $($pendingChangeResponse.id)" -ForegroundColor Gray
    Write-Host "  Operation: $($pendingChangeResponse.operation)" -ForegroundColor Gray
    Write-Host "  Resource URI: $($pendingChangeResponse.resourceUri)" -ForegroundColor Gray
    Write-Host "  Status: $($pendingChangeResponse.status)" -ForegroundColor Gray
    Write-Host "  Created By: $($pendingChangeResponse.createdBy)" -ForegroundColor Gray
    Write-Host "  Proposed Data:" -ForegroundColor Gray
    Write-Host "    $(($pendingChangeResponse.proposedData | ConvertTo-Json -Compress).Substring(0, [Math]::Min(200, ($pendingChangeResponse.proposedData | ConvertTo-Json -Compress).Length)))..." -ForegroundColor Gray
} catch {
    Write-Host "✗ Failed to get PendingChange" -ForegroundColor Red
    exit 1
}

# Step 8: Approve PendingChange (Human decision)
Write-Host "`n[Step 8] Human approves change..." -ForegroundColor Yellow
try {
    $approveBody = @{
        decision = "approved"
        comment = "Looks good! AI proposed changes are approved."
    }

    $approveResponse = Invoke-Api -Method Post -Endpoint "/api/mcp/pending-changes/$PendingChangeId/review" -Body $approveBody
    Write-Host "✓ PendingChange approved successfully" -ForegroundColor Green
    Write-Host "  Status: $($approveResponse.status)" -ForegroundColor Gray
    Write-Host "  Reviewed At: $($approveResponse.reviewedAt)" -ForegroundColor Gray
    Write-Host "  Comment: $($approveResponse.comment)" -ForegroundColor Gray

    # Extract Epic ID from result
    if ($approveResponse.result -and $approveResponse.result.id) {
        $EpicId = $approveResponse.result.id
        Write-Host "  Epic Created ID: $EpicId" -ForegroundColor Cyan
    }
} catch {
    Write-Host "✗ Failed to approve PendingChange" -ForegroundColor Red
    exit 1
}

# Step 9: Verify Epic was created
Write-Host "`n[Step 9] Verify Epic was created..." -ForegroundColor Yellow
try {
    $epicResponse = Invoke-Api -Method Get -Endpoint "/api/epics/$EpicId"
    Write-Host "✓ Epic verified successfully" -ForegroundColor Green
    Write-Host "  Epic ID: $($epicResponse.id)" -ForegroundColor Gray
    Write-Host "  Title: $($epicResponse.title)" -ForegroundColor Gray
    Write-Host "  Description: $($epicResponse.description)" -ForegroundColor Gray
    Write-Host "  Priority: $($epicResponse.priority)" -ForegroundColor Gray
    Write-Host "  Status: $($epicResponse.status)" -ForegroundColor Gray
} catch {
    Write-Host "✗ Failed to verify Epic" -ForegroundColor Red
    exit 1
}

# Step 10: Get Audit Logs
Write-Host "`n[Step 10] View Audit Logs..." -ForegroundColor Yellow
try {
    $auditLogsResponse = Invoke-Api -Method Get -Endpoint "/api/mcp/audit-logs?entityId=$EpicId&limit=10"
    Write-Host "✓ Audit logs retrieved successfully" -ForegroundColor Green
    Write-Host "  Total logs: $($auditLogsResponse.items.Count)" -ForegroundColor Gray

    foreach ($log in $auditLogsResponse.items) {
        Write-Host "  ---" -ForegroundColor Gray
        Write-Host "  Event: $($log.eventType)" -ForegroundColor Gray
        Write-Host "  Actor: $($log.actorId) ($($log.actorType))" -ForegroundColor Gray
        Write-Host "  Timestamp: $($log.timestamp)" -ForegroundColor Gray
        if ($log.metadata) {
            Write-Host "  Metadata: $(($log.metadata | ConvertTo-Json -Compress).Substring(0, [Math]::Min(100, ($log.metadata | ConvertTo-Json -Compress).Length)))..." -ForegroundColor Gray
        }
    }
} catch {
    Write-Host "  Warning: Could not retrieve audit logs" -ForegroundColor Yellow
}

# Summary
Write-Host "`n=== Test Summary ===" -ForegroundColor Cyan
Write-Host "✓ All tests passed!" -ForegroundColor Green
Write-Host ""
Write-Host "Workflow completed:" -ForegroundColor White
Write-Host "  1. User authenticated: $Username" -ForegroundColor Gray
Write-Host "  2. Project created: $ProjectId" -ForegroundColor Gray
Write-Host "  3. MCP API Key created: $($ApiKey.Substring(0, 20))..." -ForegroundColor Gray
Write-Host "  4. AI proposed Epic creation via MCP Tool" -ForegroundColor Gray
Write-Host "  5. PendingChange created: $PendingChangeId" -ForegroundColor Gray
Write-Host "  6. Human approved the change" -ForegroundColor Gray
Write-Host "  7. Epic created: $EpicId" -ForegroundColor Gray
Write-Host "  8. Audit trail recorded" -ForegroundColor Gray
Write-Host ""
Write-Host "This demonstrates the complete AI + Human collaboration workflow!" -ForegroundColor Green
Write-Host "AI can propose changes safely, and humans maintain control through approval." -ForegroundColor Green
