#!/usr/bin/env nu

# Documentation discovery module - extracts discovery phase from generate-docs.nu
# Responsible for discovering documentation sources, API endpoints, and project structure

use std log

# Main discovery orchestrator - discovers all documentation sources in the project
export def discover-all-docs [docs_config: record] {
    log info "Discovering documentation sources..."

    let start_time = (date now)

    # Find existing documentation files
    let existing_docs = find-existing-docs $docs_config.source_root

    # Analyze project structure for automatic documentation generation
    let project_structure = analyze-structure $docs_config.source_root

    # Discover configuration examples
    let config_examples = find-config-examples $docs_config.source_root

    # Find API endpoints for documentation
    let api_endpoints = if $docs_config.generate_api {
        discover-api-endpoints $docs_config.source_root
    } else {
        []
    }

    {
        status: "success"
        existing_docs: $existing_docs
        project_structure: $project_structure
        config_examples: $config_examples
        api_endpoints: $api_endpoints
        duration: ((date now) - $start_time)
    }
}

# Find existing documentation files
export def find-existing-docs [repo_root: string] {
    let doc_patterns = ["README.md", "*.md", "*.rst", "docs/*", "doc/*"]
    mut found_docs = []

    for pattern in $doc_patterns {
        let result = (do {
            ^find $repo_root -name $pattern -type f 2>/dev/null
        } | complete)

        if $result.exit_code == 0 and ($result.stdout | length) > 0 {
            let files = ($result.stdout | lines)
            $found_docs = ($found_docs | append $files)
        }
    }

    let categorized_docs = $found_docs
        | where { |doc| $doc != "" and ($doc | path exists) }
        | each {|doc|
            {
                path: $doc
                name: ($doc | path basename)
                category: (categorize-document $doc)
                size: (ls $doc | get 0.size)
            }
        }

    {
        total_docs: ($categorized_docs | length)
        readme_files: ($categorized_docs | where category == "readme")
        user_docs: ($categorized_docs | where category == "user")
        dev_docs: ($categorized_docs | where category == "dev")
        api_docs: ($categorized_docs | where category == "api")
        other_docs: ($categorized_docs | where category == "other")
        all_docs: $categorized_docs
    }
}

# Discover API endpoints for documentation
export def discover-api-endpoints [repo_root: string] {
    # This would analyze Rust source files to find API routes
    # For now, we'll return a placeholder structure

    [
        { path: "/health", method: "GET", description: "Health check endpoint" }
        { path: "/version", method: "GET", description: "System version information" }
        { path: "/workflows", method: "GET", description: "List workflows" }
        { path: "/workflows", method: "POST", description: "Create new workflow" }
        { path: "/workflows/{id}", method: "GET", description: "Get workflow details" }
        { path: "/workflows/{id}", method: "DELETE", description: "Delete workflow" }
    ]
}

# Analyze project structure for documentation generation
export def analyze-structure [repo_root: string] {
    # Find major components
    let components = [
        { name: "orchestrator", path: ($repo_root | path join "orchestrator") }
        { name: "control-center", path: ($repo_root | path join "control-center") }
        { name: "provisioning", path: ($repo_root | path join "provisioning") }
        { name: "platform", path: ($repo_root | path join "platform") }
        { name: "core", path: ($repo_root | path join "core") }
    ]

    let existing_components = ($components | where {|comp| ($comp.path | path exists) })

    # Analyze Nushell modules for documentation
    let nu_result = (do {
        ^find $repo_root -name "*.nu" -type f 2>/dev/null
    } | complete)

    let nu_modules = if $nu_result.exit_code == 0 and ($nu_result.stdout | length) > 0 {
        $nu_result.stdout | lines
    } else {
        []
    }

    # Find configuration files
    let toml_files = (do {
        ^find $repo_root -name "*.toml" -type f 2>/dev/null
    } | complete)

    let yaml_files = (do {
        ^find $repo_root -name "*.yaml" -type f 2>/dev/null
    } | complete)

    let json_files = (do {
        ^find $repo_root -name "*.json" -type f 2>/dev/null
    } | complete)

    let config_files = (
        (if $toml_files.exit_code == 0 and ($toml_files.stdout | length) > 0 { $toml_files.stdout | lines } else { [] }) |
        append (if $yaml_files.exit_code == 0 and ($yaml_files.stdout | length) > 0 { $yaml_files.stdout | lines } else { [] }) |
        append (if $json_files.exit_code == 0 and ($json_files.stdout | length) > 0 { $json_files.stdout | lines } else { [] })
    )

    {
        components: $existing_components
        nu_modules: ($nu_modules | length)
        config_files: ($config_files | length)
        has_rust_projects: (($repo_root | path join "Cargo.toml") | path exists)
        has_docker: (($repo_root | path join "Dockerfile") | path exists)
    }
}

# Find configuration examples in the repository
def find-config-examples [repo_root: string] {
    let example_patterns = ["*.example", "*.template", "examples/*", "config/*"]
    mut examples = []

    for pattern in $example_patterns {
        let result = (do {
            ^find $repo_root -name $pattern -type f 2>/dev/null
        } | complete)

        if $result.exit_code == 0 and ($result.stdout | length) > 0 {
            let files = ($result.stdout | lines)
            $examples = ($examples | append $files)
        }
    }

    return ($examples
        | where { |ex| $ex != "" }
        | each {|ex|
            {
                path: $ex
                name: ($ex | path basename)
                type: (get-config-type $ex)
            }
        })
}

# Categorize document based on filename and location
def categorize-document [doc_path: string] {
    let name = ($doc_path | path basename | str downcase)
    let path = ($doc_path | str downcase)

    if ($name == "readme.md") or ($name | str starts-with "readme") {
        return "readme"
    }

    if ($name | str contains "install") or ($name | str contains "setup") or ($name | str contains "getting") {
        return "user"
    }

    if ($name | str contains "api") or ($path | str contains "/api/") {
        return "api"
    }

    if ($name | str contains "dev") or ($name | str contains "contrib") or ($path | str contains "/dev/") {
        return "dev"
    }

    if ($name | str contains "config") or ($name | str contains "reference") {
        return "admin"
    }

    return "other"
}

# Get configuration file type
def get-config-type [config_path: string] {
    let parsed = ($config_path | path parse)
    let ext = $parsed.extension | str downcase
    match $ext {
        "toml" => "toml"
        "yaml" | "yml" => "yaml"
        "json" => "json"
        "env" => "environment"
        _ => "unknown"
    }
}
