import os
import sys
from pathlib import Path

from docutils import nodes
from docutils.parsers.rst import Directive
from sphinx import addnodes
from sphinx.errors import SphinxError
from sphinx.util.nodes import split_explicit_title, process_index_entry, set_role_source_info
from generation import generate_javascript
from htc_helpers import *

SUBMIT_CMDS = []

def find_submit_cmds(dir: str):
    subcoms = []
    jdl_man = Path(dir) / "man-pages" / "htcondor-jdl.rst"
    with open(jdl_man, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            for subcom in get_all_defined_role("subcom-def", line):
                if subcom not in subcoms:
                    subcoms.append(subcom)
    subcoms.sort()
    return subcoms

def dump(obj):
    for attr in dir(obj):
        print("obj.%s = %r" % (attr, getattr(obj, attr)))

def subcom_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    root_dir = root_dir = get_rel_path_to_root_dir(inliner)[:-1]
    subcom_name, subcom_index = custom_ext_parser(text)
    if subcom_name not in SUBMIT_CMDS:
        docname = inliner.document.settings.env.docname
        warn(f"{docname}:{lineno} | Submit command '{subcom_name}' not found in defined list. Either a typo or not defined.")
    ref_link = f"href=\"{root_dir}/man-pages/htcondor-jdl.html#" + str(subcom_name) + "\""
    return make_ref_and_index_nodes(name, subcom_name, subcom_index,
                                    ref_link, rawtext, inliner, lineno, options)

def generate_subcom_redirect_js(app):
    """Write a JS file that redirects condor_submit.html#<subcom> to htcondor-jdl.html#<subcom>."""
    if not SUBMIT_CMDS:
        warn("No submit commands to handle redirect!")
        return
    js_path = generate_javascript(app.srcdir, "subcom-redirect.js")
    subcom_list = ",\n".join(f'    "{s}"' for s in SUBMIT_CMDS)

    js_path.write_text(f"""
// Auto-generated by subcom.py — do not edit manually.
// Redirects condor_submit.html#<subcom> anchors to htcondor-jdl.html#<subcom>.

const jdl_cmds = [
{subcom_list}
];

// Magic Redirect function
function configRedirect() {{
    var hash = window.location.hash;
    if (hash && /condor_submit\\.html$/.test(window.location.pathname)) {{
        var subcom = hash.substring(1);
        if (jdl_cmds.indexOf(subcom) !== -1) {{
            window.location.replace(
                window.location.href.replace("condor_submit.html", "htcondor-jdl.html")
            );
        }}
    }}
}}

window.addEventListener('DOMContentLoaded', configRedirect);
""", encoding="utf-8")

def setup(app):
    global SUBMIT_CMDS
    SUBMIT_CMDS = find_submit_cmds(app.srcdir)
    app.add_role("subcom", subcom_role)
    app.connect("builder-inited", generate_subcom_redirect_js)

