#!/usr/bin/env nu

# Common config file finder for syntaxis scripts
#
# Finds configuration files in standard locations.
#
# SEARCH ORDER (uses first found):
#   1. .syntaxis/{filename}  - syntaxis specific config
#   2. .project/{filename}              - Generic project config
#   3. .coder/{filename}                - Documentation tracking config
#   4. {filename}                       - Current directory fallback
#
# EXAMPLES:
#   # Find config file
#   let config = (find-config "workspace.toml")
#
#   # Find with default
#   let config = (find-config-or "config.toml" "workspace.toml")
#
#   # Find database file
#   let db_path = (find-db-path "workspace.db")

# Find config file in standard locations
# Returns first existing path, or empty string if not found
export def find-config [filename: string]: nothing -> string {
    let candidates = [
        $".syntaxis/($filename)"
        $".project/($filename)"
        $".coder/($filename)"
        $filename
    ]

    let found = ($candidates | where { $in | path exists } | first)

    if ($found | is-empty) {
        ""
    } else {
        $found
    }
}

# Find config file or return default
# Returns first existing path, or default if none found
export def find-config-or [filename: string, default: string]: nothing -> string {
    let result = (find-config $filename)

    if ($result | is-empty) {
        $default
    } else {
        $result
    }
}

# Find database file in standard locations
# Returns first existing DB, or defaults to .syntaxis/ if none exist
export def find-db-path [filename: string]: nothing -> string {
    let config_path = (find-config $filename)

    if ($config_path | is-empty) {
        $".syntaxis/($filename)"
    } else {
        $config_path
    }
}

# Tests
#[test]
def test-find-config [] {
    # This would need tempdir support - skipped in basic version
    true
}
