# Compliance CLI Commands
# Provides comprehensive compliance features for GDPR, SOC2, and ISO 27001

const ORCHESTRATOR_URL = "http://localhost:8080"

# ============================================================================
# GDPR Commands
# ============================================================================

# Export personal data for a user (GDPR Article 15 - Right to Access)
export def "compliance gdpr export" [
    user_id: string  # User ID to export data for
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/gdpr/export/($user_id)"

    print $"Exporting personal data for user: ($user_id)"

    let result = (do {
        http post $url {}
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout | to json
    } else {
        error make --unspanned {
            msg: $"Failed to export data: ($result.stderr)"
        }
    }
}

# Delete personal data for a user (GDPR Article 17 - Right to Erasure)
export def "compliance gdpr delete" [
    user_id: string  # User ID to delete data for
    --reason: string = "user_request"  # Deletion reason
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/gdpr/delete/($user_id)"

    print $"Deleting personal data for user: ($user_id)"
    print $"Reason: ($reason)"

    let result = (do {
        http post $url {reason: $reason}
    } | complete)

    if $result.exit_code == 0 {
        print "✓ Data deletion completed"
        $result.stdout | to json
    } else {
        error make --unspanned {
            msg: $"Failed to delete data: ($result.stderr)"
        }
    }
}

# Rectify personal data for a user (GDPR Article 16 - Right to Rectification)
export def "compliance gdpr rectify" [
    user_id: string  # User ID
    --field: string  # Field to rectify
    --value: string  # New value
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    if ($field | is-empty) or ($value | is-empty) {
        error make --unspanned {
            msg: "Both --field and --value must be provided"
        }
    }

    let url = $"($orchestrator_url)/api/v1/compliance/gdpr/rectify/($user_id)"
    let corrections = {($field): $value}

    print $"Rectifying data for user: ($user_id)"
    print $"Field: ($field) -> ($value)"

    let result = (do {
        http post $url {corrections: $corrections}
    } | complete)

    if $result.exit_code == 0 {
        print "✓ Data rectification completed"
    } else {
        error make --unspanned {
            msg: $"Failed to rectify data: ($result.stderr)"
        }
    }
}

# Export data for portability (GDPR Article 20 - Right to Data Portability)
export def "compliance gdpr portability" [
    user_id: string  # User ID
    --format: string = "json"  # Export format (json, csv, xml)
    --output: string  # Output file path
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/gdpr/portability/($user_id)"

    print $"Exporting data for portability: ($user_id)"
    print $"Format: ($format)"

    let result = (do {
        http post $url {format: $format}
    } | complete)

    if $result.exit_code == 0 {
        if ($output | is-empty) {
            $result.stdout
        } else {
            $result.stdout | save $output
            print $"✓ Data exported to: ($output)"
        }
    } else {
        error make --unspanned {
            msg: $"Failed to export data: ($result.stderr)"
        }
    }
}

# Record objection to processing (GDPR Article 21 - Right to Object)
export def "compliance gdpr object" [
    user_id: string  # User ID
    processing_type: string  # Type of processing to object (direct_marketing, profiling, etc.)
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/gdpr/object/($user_id)"

    print $"Recording objection for user: ($user_id)"
    print $"Processing type: ($processing_type)"

    let result = (do {
        http post $url {processing_type: $processing_type}
    } | complete)

    if $result.exit_code == 0 {
        print "✓ Objection recorded"
    } else {
        error make --unspanned {
            msg: $"Failed to record objection: ($result.stderr)"
        }
    }
}

# ============================================================================
# SOC2 Commands
# ============================================================================

# Generate SOC2 compliance report
export def "compliance soc2 report" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
    --output: string  # Output file path
] {
    let url = $"($orchestrator_url)/api/v1/compliance/soc2/report"

    print "Generating SOC2 compliance report..."

    let result = (do {
        http get $url
    } | complete)

    if $result.exit_code == 0 {
        if ($output | is-empty) {
            $result.stdout | to json
        } else {
            $result.stdout | to json | save $output
            print $"✓ SOC2 report saved to: ($output)"
        }
    } else {
        error make --unspanned {
            msg: $"Failed to generate SOC2 report: ($result.stderr)"
        }
    }
}

# List SOC2 Trust Service Criteria
export def "compliance soc2 controls" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/soc2/controls"

    let result = (do {
        http get $url | get controls
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to list controls: ($result.stderr)"
        }
    }
}

# ============================================================================
# ISO 27001 Commands
# ============================================================================

# Generate ISO 27001 compliance report
export def "compliance iso27001 report" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
    --output: string  # Output file path
] {
    let url = $"($orchestrator_url)/api/v1/compliance/iso27001/report"

    print "Generating ISO 27001 compliance report..."

    let result = (do {
        http get $url
    } | complete)

    if $result.exit_code == 0 {
        if ($output | is-empty) {
            $result.stdout | to json
        } else {
            $result.stdout | to json | save $output
            print $"✓ ISO 27001 report saved to: ($output)"
        }
    } else {
        error make --unspanned {
            msg: $"Failed to generate ISO 27001 report: ($result.stderr)"
        }
    }
}

# List ISO 27001 Annex A controls
export def "compliance iso27001 controls" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/iso27001/controls"

    let result = (do {
        http get $url | get controls
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to list controls: ($result.stderr)"
        }
    }
}

# List identified risks
export def "compliance iso27001 risks" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/iso27001/risks"

    let result = (do {
        http get $url | get risks
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to list risks: ($result.stderr)"
        }
    }
}

# ============================================================================
# Data Protection Commands
# ============================================================================

# Verify data protection controls
export def "compliance protection verify" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/protection/verify"

    print "Verifying data protection controls..."

    let result = (do {
        http get $url | to json
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to verify protection: ($result.stderr)"
        }
    }
}

# Classify data
export def "compliance protection classify" [
    data: string  # Data to classify
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/protection/classify"

    let result = (do {
        http post $url {data: $data} | get classification
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to classify data: ($result.stderr)"
        }
    }
}

# ============================================================================
# Access Control Commands
# ============================================================================

# List available roles
export def "compliance access roles" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/access/roles"

    let result = (do {
        http get $url | get roles
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to list roles: ($result.stderr)"
        }
    }
}

# Get permissions for a role
export def "compliance access permissions" [
    role: string  # Role name
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/access/permissions/($role)"

    let result = (do {
        http get $url | get permissions
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to get permissions: ($result.stderr)"
        }
    }
}

# Check if role has permission
export def "compliance access check" [
    role: string  # Role name
    permission: string  # Permission to check
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/access/check"

    let check_result = (do {
        http post $url {role: $role, permission: $permission}
    } | complete)

    if $check_result.exit_code == 0 {
        $check_result.stdout | get allowed
    } else {
        error make --unspanned {
            msg: $"Failed to check permission: ($check_result.stderr)"
        }
    }
}

# ============================================================================
# Incident Response Commands
# ============================================================================

# Report a security incident
export def "compliance incident report" [
    --severity: string  # Incident severity (critical, high, medium, low)
    --type: string  # Incident type (data_breach, unauthorized_access, etc.)
    --description: string  # Incident description
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    if ($severity | is-empty) or ($type | is-empty) or ($description | is-empty) {
        error make --unspanned {
            msg: "All parameters (--severity, --type, --description) are required"
        }
    }

    let url = $"($orchestrator_url)/api/v1/compliance/incidents"

    print $"Reporting ($severity) incident of type ($type)"

    let result = (do {
        http post $url {
            severity: $severity,
            incident_type: $type,
            description: $description,
            affected_systems: [],
            affected_users: [],
            reported_by: "cli-user"
        }
    } | complete)

    if $result.exit_code == 0 {
        let response = ($result.stdout)
        print $"✓ Incident reported: ($response.incident_id)"
        $response.incident_id
    } else {
        error make --unspanned {
            msg: $"Failed to report incident: ($result.stderr)"
        }
    }
}

# List security incidents
export def "compliance incident list" [
    --severity: string  # Filter by severity
    --status: string  # Filter by status
    --type: string  # Filter by type
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    mut query_params = []

    if not ($severity | is-empty) {
        $query_params = ($query_params | append $"severity=($severity)")
    }

    if not ($status | is-empty) {
        $query_params = ($query_params | append $"status=($status)")
    }

    if not ($type | is-empty) {
        $query_params = ($query_params | append $"incident_type=($type)")
    }

    let query_string = if ($query_params | length) > 0 {
        $"?($query_params | str join '&')"
    } else {
        ""
    }

    let url = $"($orchestrator_url)/api/v1/compliance/incidents($query_string)"

    let result = (do {
        http get $url
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to list incidents: ($result.stderr)"
        }
    }
}

# Get incident details
export def "compliance incident show" [
    incident_id: string  # Incident ID
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/incidents/($incident_id)"

    let result = (do {
        http get $url | to json
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to get incident: ($result.stderr)"
        }
    }
}

# ============================================================================
# Combined Reporting
# ============================================================================

# Generate combined compliance report
export def "compliance report" [
    --format: string = "json"  # Output format (json, yaml)
    --output: string  # Output file path
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/reports/combined"

    print "Generating combined compliance report..."
    print "This includes GDPR, SOC2, and ISO 27001 compliance status"

    let result = (do {
        http get $url
    } | complete)

    if $result.exit_code == 0 {
        let formatted = if $format == "yaml" {
            $result.stdout | to yaml
        } else {
            $result.stdout | to json
        }

        if ($output | is-empty) {
            $formatted
        } else {
            $formatted | save $output
            print $"✓ Compliance report saved to: ($output)"
        }
    } else {
        error make --unspanned {
            msg: $"Failed to generate report: ($result.stderr)"
        }
    }
}

# Check compliance health status
export def "compliance health" [
    --orchestrator-url: string = $ORCHESTRATOR_URL  # Orchestrator URL
] {
    let url = $"($orchestrator_url)/api/v1/compliance/health"

    let result = (do {
        http get $url
    } | complete)

    if $result.exit_code == 0 {
        $result.stdout
    } else {
        error make --unspanned {
            msg: $"Failed to check health: ($result.stderr)"
        }
    }
}

# ============================================================================
# Helper Functions
# ============================================================================

# Show compliance command help
export def "compliance help" [] {
    print "
Compliance CLI - GDPR, SOC2, and ISO 27001 Features

Usage:
  compliance <category> <command> [options]

Categories:
  gdpr        - GDPR compliance (data subject rights)
  soc2        - SOC2 Trust Service Criteria
  iso27001    - ISO 27001 Annex A controls
  protection  - Data protection controls
  access      - Access control matrix
  incident    - Incident response
  report      - Combined compliance reporting
  health      - Health check

Examples:
  # Export user data (GDPR)
  compliance gdpr export user123

  # Generate SOC2 report
  compliance soc2 report --output soc2-report.json

  # Generate ISO 27001 report
  compliance iso27001 report --output iso27001-report.json

  # Report security incident
  compliance incident report --severity critical --type data_breach --description \"Unauthorized access detected\"

  # Generate combined report
  compliance report --output compliance-report.json

For detailed help on a specific command, use:
  help compliance <category> <command>
"
}
