# Break-Glass Emergency Access Commands
#
# Provides CLI interface for break-glass emergency access system

# Request emergency access
export def "break-glass request" [
    reason: string              # Emergency reason (brief)
    --justification: string     # Detailed justification (required)
    --resources: list<string> = [] # Target resources
    --permissions: list<string> = [] # Requested permissions
    --duration: duration = 4hr  # Maximum session duration
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    if ($justification | is-empty) {
        error make {msg: "Justification is required for break-glass requests"}
    }

    # Get current user info
    let requester = {
        id: (whoami)
        email: $"(whoami)@example.com"
        name: (whoami)
        teams: ["operations"]
        roles: ["Operator"]
    }

    # Convert permissions list to structured format
    let structured_permissions = $permissions | each {|p|
        let parts = ($p | split row ":")
        {
            resource: ($parts | get 0)
            action: ($parts | get 1? | default "admin")
            scope: null
        }
    }

    # Convert duration to hours
    let duration_hours = ($duration | into int) / (1hr | into int)

    let payload = {
        requester: $requester
        reason: $reason
        justification: $justification
        target_resources: $resources
        requested_permissions: $structured_permissions
        duration_hours: $duration_hours
    }

    print $"🚨 Requesting emergency access..."
    print $"   Reason: ($reason)"
    print $"   Duration: ($duration)"
    print $"   Resources: ($resources | str join ', ')"

    let response = (http post $"($orchestrator)/api/v1/break-glass/request" $payload)

    print $"✅ Request created: ($response.request_id)"
    print $"   Status: ($response.status)"
    print $"   Expires: ($response.expires_at)"
    print ""
    print $"⏳ Waiting for approval from 2+ approvers..."

    $response
}

# Approve emergency request
export def "break-glass approve" [
    request_id: string          # Request ID to approve
    --reason: string = "Approved" # Approval reason
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    # Get current user info
    let approver = {
        id: (whoami)
        email: $"(whoami)@example.com"
        name: (whoami)
        teams: ["security"]
        roles: ["SecurityOfficer"]
    }

    # Get IP address
    let ip_address = "127.0.0.1"

    let payload = {
        approver: $approver
        reason: $reason
        ip_address: $ip_address
    }

    print $"✅ Approving request ($request_id)..."

    let response = (http post $"($orchestrator)/api/v1/break-glass/requests/($request_id)/approve" $payload)

    if $response.approved {
        print $"✅ Request fully approved!"
        print $"   All required approvals received"
        print $"   Ready for activation"
    } else {
        print $"⏳ Approval recorded"
        print $"   ($response.message)"
    }

    $response
}

# Deny emergency request
export def "break-glass deny" [
    request_id: string          # Request ID to deny
    --reason: string = "Denied" # Denial reason
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    # Get current user info
    let denier = {
        id: (whoami)
        email: $"(whoami)@example.com"
        name: (whoami)
        teams: ["security"]
        roles: ["SecurityOfficer"]
    }

    let payload = {
        denier: $denier
        reason: $reason
    }

    print $"❌ Denying request ($request_id)..."

    http post $"($orchestrator)/api/v1/break-glass/requests/($request_id)/deny" $payload | ignore

    print $"✅ Request denied"
}

# Activate approved session
export def "break-glass activate" [
    request_id: string          # Request ID to activate
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    print $"🔓 Activating emergency session for request ($request_id)..."

    let token = (http post $"($orchestrator)/api/v1/break-glass/requests/($request_id)/activate" {})

    print $"✅ Emergency session activated!"
    print $"   Session ID: ($token.session_id)"
    print $"   Expires: ($token.expires_at)"
    print $"   Token: ($token.access_token | str substring 0..50)..."
    print ""
    print $"⚠️  This session is logged and monitored"
    print $"⚠️  All actions will be audited"
    print ""
    print $"Export token:"
    print $"   export EMERGENCY_TOKEN=($token.access_token)"

    $token
}

# Revoke active session
export def "break-glass revoke" [
    session_id: string          # Session ID to revoke
    --reason: string = "Manual revocation" # Revocation reason
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    let payload = {
        reason: $reason
    }

    print $"🔒 Revoking session ($session_id)..."

    http post $"($orchestrator)/api/v1/break-glass/sessions/($session_id)/revoke" $payload | ignore

    print $"✅ Session revoked"
}

# List pending requests
export def "break-glass list-requests" [
    --status: string = "pending" # Filter by status (pending, all)
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    let pending_only = ($status == "pending")

    print $"📋 Listing break-glass requests..."

    let requests = (http get $"($orchestrator)/api/v1/break-glass/requests?pending_only=($pending_only)")

    if ($requests | is-empty) {
        print "No requests found"
        return []
    }

    $requests | select id status requester.email reason created_at expires_at
}

# List active sessions
export def "break-glass list-sessions" [
    --active-only: bool = false # Show only active sessions
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    print $"📋 Listing break-glass sessions..."

    let sessions = (http get $"($orchestrator)/api/v1/break-glass/sessions?active_only=($active_only)")

    if ($sessions | is-empty) {
        print "No sessions found"
        return []
    }

    $sessions | select id status request.requester.email activated_at expires_at
}

# Show session details
export def "break-glass show" [
    session_id: string          # Session ID to show
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    print $"🔍 Fetching session details for ($session_id)..."

    let session = (http get $"($orchestrator)/api/v1/break-glass/sessions/($session_id)")

    print ""
    print $"Session ID: ($session.id)"
    print $"Status: ($session.status)"
    print $"Requester: ($session.request.requester.email)"
    print $"Reason: ($session.request.reason)"
    print ""
    print "Approvals:"
    $session.approvals | each {|a|
        print $"  - ($a.approver.email) at ($a.approved_at)"
    }
    print ""
    print $"Activated: ($session.activated_at)"
    print $"Expires: ($session.expires_at)"
    print ""
    print $"Actions performed: ($session.actions | length)"

    $session
}

# Query break-glass audit logs
export def "break-glass audit" [
    --from: datetime            # Start time
    --to: datetime              # End time
    --session-id: string        # Filter by session ID
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    print $"📜 Querying break-glass audit logs..."

    mut params = []

    if not ($from | is-empty) {
        $params = ($params | append $"from=($from | date to-record | get year)-($from | date to-record | get month)-($from | date to-record | get day)")
    }

    if not ($to | is-empty) {
        $params = ($params | append $"to=($to | date to-record | get year)-($to | date to-record | get month)-($to | date to-record | get day)")
    }

    if not ($session_id | is-empty) {
        $params = ($params | append $"session_id=($session_id)")
    }

    let query_string = if ($params | is-empty) { "" } else { $"?($params | str join '&')" }

    let logs = (http get $"($orchestrator)/api/v1/break-glass/audit($query_string)")

    if ($logs | is-empty) {
        print "No audit logs found"
        return []
    }

    $logs | select event_id event_type session_id user.email timestamp
}

# Show break-glass statistics
export def "break-glass stats" [
    --orchestrator: string = "http://localhost:8080" # Orchestrator URL
] {
    print $"📊 Fetching break-glass statistics..."

    let stats = (http get $"($orchestrator)/api/v1/break-glass/statistics")

    print ""
    print "Approval Statistics:"
    print $"  Total requests: ($stats.approval.total_requests)"
    print $"  Pending: ($stats.approval.pending_requests)"
    print $"  Approved: ($stats.approval.approved_requests)"
    print $"  Denied: ($stats.approval.denied_requests)"
    print $"  Expired: ($stats.approval.expired_requests)"
    print ""
    print "Session Statistics:"
    print $"  Total sessions: ($stats.session.total_sessions)"
    print $"  Active: ($stats.session.active_sessions)"
    print $"  Revoked: ($stats.session.revoked_sessions)"
    print $"  Expired: ($stats.session.expired_sessions)"
    print $"  Total actions: ($stats.session.total_actions)"
    print ""
    print "Revocation Monitoring:"
    print $"  Enabled: ($stats.revocation.monitoring_enabled)"
    print $"  Check interval: ($stats.revocation.check_interval_seconds)s"

    $stats
}

# Break-glass help
export def "break-glass help" [] {
    print "Break-Glass Emergency Access System"
    print ""
    print "Commands:"
    print "  request      - Request emergency access"
    print "  approve      - Approve emergency request"
    print "  deny         - Deny emergency request"
    print "  activate     - Activate approved session"
    print "  revoke       - Revoke active session"
    print "  list-requests - List pending requests"
    print "  list-sessions - List active sessions"
    print "  show         - Show session details"
    print "  audit        - Query audit logs"
    print "  stats        - Show statistics"
    print ""
    print "Examples:"
    print "  # Request emergency access"
    print "  break-glass request 'Production outage' --justification 'Database cluster down' --resources ['db/*'] --duration 2hr"
    print ""
    print "  # Approve request"
    print "  break-glass approve <request_id> --reason 'Emergency confirmed'"
    print ""
    print "  # Activate session"
    print "  break-glass activate <request_id>"
    print ""
    print "  # Revoke session"
    print "  break-glass revoke <session_id> --reason 'Emergency resolved'"
}
