#!/usr/bin/env python3
# ollie:parallel read
# description: Find all references to symbol at position. Returns file:line:col per reference.
# Args: <file> <line> <col>

import os
import sys
sys.path.insert(0, os.path.join(os.environ['OLLIE'], 's', os.environ['OLLIE_SESSION_ID'], 't'))

from _lib.lsp.client import request

if len(sys.argv) < 4:
    print("usage: lsp_references <file> <line> <col>")
    sys.exit(1)

filepath = os.path.abspath(sys.argv[1])
line = int(sys.argv[2]) - 1
col = int(sys.argv[3]) - 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)")
