#!/usr/bin/env python3
# ollie:parallel read
# args_json: {"type":"object","required":["path","line","col"],"properties":{"path":{"type":"string","description":"Absolute file path"},"line":{"type":"string","description":"Line number (1-indexed)"},"col":{"type":"string","description":"Column number (1-indexed)"}}}
# ollie:prompt
# ## lsp_references
#
# Find all references to symbol at position. Capped at 50.
#
# **Args**: `[path, line, col]`
#
# ```
# lsp_references(path="/abs/path.go", line="42", col="10")
# ```
#
# **Returns**: `file:line:col` per reference.
#
# **Prefer over `file_grep`** for semantic references — won't match comments, strings, or unrelated identifiers.
# ollie:end

import os
import sys
sys.path.insert(0, os.environ.get('OLLIE_TOOLS_PATH', os.path.dirname(os.path.abspath(__file__))))

from _lib.args import parse_args
from _lib.lsp.client import request

args = parse_args()
filepath = os.path.abspath(args.require("path"))
line = int(args.require("line")) - 1
col = int(args.require("col")) - 1

result = request("references", file=filepath, line=line, col=col)

if not result:
    print("(no references found)")
    sys.exit(0)

total = len(result)
cap = 50
refs = result[:cap] if total > cap else result

for loc in refs:
    uri = loc.get("uri", "")
    path = uri[7:] if uri.startswith("file://") else uri
    pos = loc.get("range", {}).get("start", {})
    ln = pos.get("line", 0) + 1
    ch = pos.get("character", 0) + 1
    print(f"{path}:{ln}:{ch}")

if total > cap:
    print(f"\n(showing {cap} of {total} references)")
else:
    print(f"\n({total} references)")
