import argparse
import json
import sys
from .checker import check_backlink

def main():
    parser = argparse.ArgumentParser(description="Backlink checker CLI tool")
    parser.add_argument("target", help="Target domain to look for in backlinks")
    parser.add_argument("inputs", nargs="+", help="One or more URLs or a .txt/.csv file with URLs")
    parser.add_argument("--output", "-o", help="Optional output JSON file")
    args = parser.parse_args()

    urls = []

    # Check if input is file or direct URLs
    for inp in args.inputs:
        if inp.endswith(".txt") or inp.endswith(".csv"):
            try:
                with open(inp, "r") as f:
                    for line in f:
                        line = line.strip()
                        if line:
                            urls.append(line)
            except Exception as e:
                print(f"Error reading file {inp}: {e}", file=sys.stderr)
        else:
            urls.append(inp)

    results = [check_backlink(url, args.target) for url in urls]

    if args.output:
        with open(args.output, "w") as f:
            json.dump(results, f, indent=2)
    else:
        print(json.dumps(results, indent=2))
