import importlib.resources


def get_version():
    try:
        ref = importlib.resources.files("sentipede").joinpath("version.txt")
        with importlib.resources.as_file(ref) as path:
            return path.read_text().strip()
    except Exception:
        return "unknown"


def _load_template() -> str:
    try:
        ref = importlib.resources.files("sentipede.templates").joinpath("layout.html")
        return ref.read_text(encoding="utf-8")
    except Exception:
        return """<!DOCTYPE html>
<html><body>
<pre>{displaypath}</pre>
{file_list}
</body></html>"""


HTML_TEMPLATE = _load_template()


def render_listing(displaypath, files, base_url):
    items_html = ""
    if displaypath != "/":
        items_html += '<a href=".." class="dir-link">.. [UP]</a>'

    for name, size, is_dir, is_recent in files:
        if is_dir:
            items_html += f'<a href="{name}/" class="dir-link">📁: {name}/</a>'
        else:
            commands_def = [
                ("CURL",         "curl -LO {BASE_URL}/{name}",                       "linux"),
                ("WGET",         "wget {BASE_URL}/{name}",                            "linux"),
                ("PYTHON3",      'python3 -c "..."',                                  "linux"),
                ("PERL",         'perl -MLWP::Simple -e "..."',                       "linux"),
                ("BUSYBOX",      "busybox wget {BASE_URL}/{name} -O {name}",          "linux"),
                ("POWERSHELL",     "iwr -useb {BASE_URL}/{name} -OutFile {name}",     "windows"),
                ("POWERSHELL_NET", "WebClient.DownloadFile(...)",                      "windows"),
                ("CERTUTIL",       "certutil -urlcache -f {BASE_URL}/{name} {name}",  "windows"),
                ("BITSADMIN",      "bitsadmin /transfer ...",                          "windows"),
            ]

            rows = ""
            for label, cmd, os_tag in commands_def:
                rows += f'''
                <div class="cmd-line cmd-row" data-os="{os_tag}">
                    <button class="copy-btn" onclick="copyExfilCmd(this)">{label}</button>
                    <div class="code-block"><code class="exfil-cmd" data-file="{name}" data-type="{label}">{cmd}</code></div>
                </div>
                '''

            sparkle = ' ✨' if is_recent else ''

            items_html += f'''
            <details>
                <summary>
                    <span>📄: {name}{sparkle}</span>
                    <span style="color: #fbf7e0; font-size: 0.8em;">{size}</span>
                </summary>
                <div class="content-wrapper">
                    {rows}
                </div>
            </details>
            '''

    version = get_version()

    return HTML_TEMPLATE.format(
        displaypath=displaypath,
        file_list=items_html,
        version=version
    )