import csv
import sys
import os
from urllib.parse import urlparse, parse_qsl, unquote

FILE_NAME = "query_params_log.csv"

# Zero-width space to break hyperlink detection in Numbers
ZWSP = "\u200b"

def write_header_if_needed():
    if not os.path.exists(FILE_NAME):
        with open(FILE_NAME, mode="w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["URL", "Parameter", "Value"])

def break_hyperlink(url):
    # Insert invisible character after https:// or http://
    if url.startswith("https://"):
        return "https://" + ZWSP + url[len("https://"):]
    elif url.startswith("http://"):
        return "http://" + ZWSP + url[len("http://"):]
    return url

def append_grouped_params(url):
    if not url.startswith("http"):
        print("⚠️ Invalid URL ignored")
        return

    parsed = urlparse(url)
    params = parse_qsl(parsed.query, keep_blank_values=True)

    if not params:
        print("⚠️ No parameters found.")
        return

    safe_url = break_hyperlink(url)

    with open(FILE_NAME, mode="a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)

        first = True
        for k, v in params:
            if first:
                writer.writerow([safe_url, unquote(k), unquote(v)])
                first = False
            else:
                writer.writerow(["", unquote(k), unquote(v)])

        writer.writerow(["", "", ""])

def main():
    if len(sys.argv) > 1:
        url = sys.argv[1].strip()
    else:
        url = input("Paste GET URL: ").strip()

    write_header_if_needed()
    append_grouped_params(url)
    print("✅ URL saved without making it clickable in Numbers")

if __name__ == "__main__":
    main()
