#!/usr/bin/env python3
import argparse
import json
import os
import sys
import uuid
from pathlib import Path

# CONFIGURATION
JSON_DB        = '/var/log/share_scan.json'
SHARE_DIR      = Path('/var/www/html/share')
BASE_URL       = 'https://czernobog.pl/share'

# Ensure share directory exists
SHARE_DIR.mkdir(parents=True, exist_ok=True)

def load_db():
    with open(JSON_DB) as f:
        return json.load(f)['entries']

def relevancy(path, keywords):
    score = 0
    low = path.lower()
    for kw in keywords:
        if kw.lower() in low:
            score += low.count(kw.lower())
    return score

def find_matches(entries, keywords):
    scored = []
    for e in entries:
        score = relevancy(e['path'], keywords)
        if score > 0:
            scored.append((score, e['path']))
    scored.sort(reverse=True, key=lambda x: x[0])
    return [p for _, p in scored]

def interactive_select(candidates):
    print("Search results:")
    for idx, p in enumerate(candidates, 1):
        print(f" {idx:3d}. {p}")
    sel = input("\nSelect files (e.g. 1,3-5): ").strip()
    nums = set()
    for part in sel.split(','):
        if '-' in part:
            a,b = part.split('-',1)
            nums.update(range(int(a), int(b)+1))
        else:
            nums.add(int(part))
    return [candidates[i-1] for i in sorted(nums) if 1 <= i <= len(candidates)]

def publish(paths):
    urls = []
    for path in paths:
        token = uuid.uuid4().hex
        link = SHARE_DIR / token
        try:
            os.symlink(path, link)
        except FileExistsError:
            pass
        urls.append(f"{BASE_URL}/{token}")
    return urls

def main():
    parser = argparse.ArgumentParser(description="Search and share files from JSON DB")
    parser.add_argument('keywords', nargs='*',
                        help='Search keywords (interactive if omitted)')
    parser.add_argument('-n','--count', type=int, default=10,
                        help='How many top results to share')
    args = parser.parse_args()

    if not args.keywords:
        # Interactive: ask for query
        q = input("Enter search keywords (space-separated): ").strip().split()
        args.keywords = q

    entries   = load_db()
    matches   = find_matches(entries, args.keywords)
    top_n     = matches[:args.count]

    if sys.stdin.isatty():
        # interactive selection
        sel = interactive_select(top_n)
    else:
        # non-interactive: share all top_n
        sel = top_n

    urls = publish(sel)
    for u in urls:
        print(u)

if __name__=='__main__':
    main()
