#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

%modern

%requires qore >= 1.0

%requires Qdx
%requires astparser

%exec-class qdx

const Opts = {
    "dox":        "d,dox",
    "define":     "D,define=s@",
    "extra_pfx":  "X,extra-prefix=s",
    "extra":      "E,extra-files=s@",
    "help":       "h,help",
    "keepdollar": "k,keep-dollar",
    "moddx":      "M,module-dx=s",
    "nmp":        "N,no-mainpage",
    "post":       "p,post",
    "src_root":   "T,top-srcdir=s",
    "strict":     "S,strict-tables",
    "tag":        "t,tag=s@",
    "tex":        "x,posttex=s@",          # use TeX syntax for "post" processing
};

class qdx {
    private {
        bool post;
        bool links;
        bool svc;
        bool help;
        hash o;
        *string sname;
        *string psname;
        string build;
        string qorever;

        const DefaultExtraPrefix = "../doxygen/";
    }

    public {
        const QoreVer = sprintf("%d.%d.%d", Qore::VersionMajor, Qore::VersionMinor, Qore::VersionSub);
    }

    constructor() {
        GetOpt g(Opts);
        o = {
            "extra_pfx": DefaultExtraPrefix,
        } + g.parse3(\ARGV);

        if (o.help || ARGV.empty())
            usage();

        if (o.post) {
            map postProcess($1), ARGV;
            return;
        }

        if (o.moddx) {
            if (ARGV.size() < 2)
                usage();
            doModDx(ARGV[0], ARGV[1]);
            return;
        }

        if (o.dox) {
            doDox(ARGV[0], ARGV[1]);
            return;
        }

        if (o.tex) {
            map postProcess($1, True), ARGV;
            return;
        }
        if (ARGV.size() < 2)
            usage();
        processQore(ARGV[0], ARGV[1]);
    }

    static usage() {
      printf("usage: %s [options] <infile> <outfile>
  -d,--dox            process doxygen files
  -D,--define=ARG     define symbol for conditional parsing (repeatable)
  -M,--module-dx=ARG  prepare doxyfile module template; ARG=<src>:<trg>
  -N,--no-mainpage    change @mainpage to @page
  -p,--post           post process files
  -k,--keep-dollar    keep $ signs when post-processing
  -S,--strict-tables  treat documentation table issues as errors
  -t,--tag=ARG        tag argument for doxyfile
  -T,--top-srcdir=ARG the top source directory
  -h,--help           this help text
  Env: QORE_DOC_DEFINES=NAME[,NAME...] for conditional parsing symbols
", get_script_name());
      exit(1);
    }

    private string getQoreVersion() {
        return qorever ?? sprintf("%d.%d.%d", Qore::VersionMajor, Qore::VersionMinor, Qore::VersionSub);
    }

    private checkNames(string fn, string ofn) {
        if (fn === ofn) {
            stderr.printf("OUTPUT-ERROR: input and output files are the same: %y", fn);
            exit(1);
        }
    }

    private list<string> parseDefines(*string defs) {
        if (!exists defs) {
            return ();
        }
        list<string> result = ();
        foreach string part in (defs.split(",")) {
            string trimmed = trim(part);
            if (!trimmed.length()) {
                continue;
            }
            int eq_pos = trimmed.find("=");
            if (eq_pos >= 0) {
                trimmed = trim(trimmed.substr(0, eq_pos));
            }
            if (trimmed.length()) {
                result += trimmed;
            }
        }
        return result;
    }

    doModDx(string fn, string ofn) {
        checkNames(fn, ofn);

        (*string src, *string trg) = (o.moddx =~ x/([^:]+):(.*)/);
        if (!exists trg) {
            stderr.printf("MODULE-ERROR: --module-dx argument %y is not in format <src>:<trg>\n", o.moddx);
            exit(1);
        }
        #printf("src: %y trg: %y src_root: %y ofn: %y\n", src, trg, o.src_root, ofn);

        # get module name and version (the easy way)
        string name = basename(src);
        # remove ".qm" suffix for files
        name =~ s/\.qm$//;

        Program p();
        p.define("QORE_QDX_RUN", 1);
        string msrc = sprintf("%%requires %s\nhash sub get() { return get_module_hash().'%s'; }\n", src, name);
        p.parse(msrc, "mod");
        hash<auto> h = p.callFunction("get");

        # issue #2966: if module is a directory, then get all relevant files for trg / {input}
        if (is_dir(src)) {
            string trg_dir = dirname(trg) + DirSep;
            list<string> trg_list;
            foreach string file in (glob(src + DirSep + "*")) {
                if (file =~ /\.qm$/ || file =~ /\.qc$/ || file =~ /\.ql$/) {
                    file = sprintf("%s%s.dox.h", trg_dir, basename(file));
                    trg_list += file;
                }
            }

            # replace target list for {input}
            trg = trg_list.join(" ");
        }

        InputStreamLineIterator i(new FileInputStream(fn), NOTHING, NOTHING, False);

        StreamWriter w(new FileOutputStream(ofn));

        # get tags substitution string
        string tags = o.tag ? o.tag.join(" ") : "";

        while (i.next()) {
            string line = i.getValue();

            if (line =~ /{module}/)
                line = replace(line, "{module}", name);
            else if (line =~ /{input}/)
                line = replace(line, "{input}", trg);
            else if (line =~ /{version}/)
                line = replace(line, "{version}", h.version);
            else if (line =~ /{tags}/)
                line = replace(line, "{tags}", tags);
            else if (line =~ /{qore_version}/)
                line = replace(line, "{qore_version}", QoreVer);
            else if (line =~ /{qore_src_dir}/) {
                line = replace(line, "{qore_src_dir}", o.src_root);
            } else if (line =~ /{extra_files}/) {
                string extra;
                if (o.extra) {
                    extra = (map sprintf("%s%s", o.extra_pfx, $1), o.extra).join(" ");
                }
                line = replace(line, "{extra_files}", extra ?? "");
            }

            w.write(line);
        }
    }

    doDox(string fn, string ofn) {
        printf("processing %y -> %y\n", fn, ofn);

        DocumentTableInputStreamLineIterator i(new FileInputStream(fn), NOTHING, NOTHING, False, fn);

        StreamWriter w(new FileOutputStream(ofn));

        while (i.next()) {
            string line = i.getValue();

            if (line =~ /{qore_version}/)
                line = replace(line, "{qore_version}", QoreVer);

            w.write(line);
        }

        reportTableWarnings(i.takeTableWarnings());
    }

    #! Reports documentation table format warnings; see design/doc-tables.md
    /** @param warnings the warnings to report

        @note exits with a non-zero status if \c --strict-tables was given and any warning was
        reported
    */
    private reportTableWarnings(list<string> warnings) {
        if (warnings.empty()) {
            return;
        }

        string label = o.strict ? "ERROR" : "WARNING";
        map stderr.printf("%s: %s\n", label, $1), warnings;

        if (o.strict) {
            stderr.printf("ERROR: %d documentation table issue%s found; see design/doc-tables.md\n",
                warnings.size(), warnings.size() == 1 ? "" : "s");
            exit(1);
        }
    }

    private postProcess(string ifn, bool tex = False) {
        *hash h = hstat(ifn);
        if (h.type == "DIRECTORY") {
            Dir d();
            d.chdir(ifn);
            list l = d.listFiles("\\.(html|js)$"); #");
            map postProcessIntern(ifn + "/" + $1, tex), l;
        }
        else
            map postProcessIntern($1, tex), glob(ifn);
    }

    postProcessIntern(string ifn, bool tex) {
        FileInputStream inf(ifn);
        InputStreamLineIterator ins = tex
            ? new QorePostProcessingTexInputStreamLineIterator(inf)
            : new QorePostProcessingInputStreamLineIterator(inf);

        string ofn = ifn + ".new";

        #printf("processing API file %s\n", ifn);

        StreamWriter w(new FileOutputStream(ofn));

        on_success rename(ofn, ifn);

        map w.write($1), ins;
    }

    fixParam(reference line) {
        if (line =~ /@param/) {
            line =~ s/([^\/\*])\*/1__7_ /g;
            line =~ s/\$/__6_/g;
        }
        if (exists (*string str = regex_extract(line, "(" + sname + "\\.[a-z0-9_]+)", RE_Caseless)[0])) {
            string nstr = str;
            #printf("str=%n nstr=%n\n", str, nstr);
            nstr =~ s/\./__4_/g;
            line = replace(line, str, nstr);
        }
    }

    processQore(string fn, string nn) {
        checkNames(fn, nn);

        # issue #2966: process module directories
        if (is_dir(fn)) {
            string targ_dir = dirname(nn);
            foreach string file in (glob(fn + DirSep + "*")) {
                if (file =~ /\.qm$/ || file =~ /\.qc$/ || file =~ /\.ql$/) {
                    string file_nn = sprintf("%s/%s.dox.h", targ_dir, basename(file));
                    processQoreFile(file, file_nn);
                }
            }
        } else {
            processQoreFile(fn, nn);
        }
    }

    #! Processes a Qore file to doxygen-compatible output using AstProcessor
    private processQoreFile(string fn, string nn) {
        printf("processing %y -> %y\n", fn, nn);

        # Read the source file
        string code = ReadOnlyFile::readTextFile(fn);

        # Parse with astparser
        AstParser parser();
        parser.setConditionalParsing(True);
        list<string> defines = ();
        *string env_defines = getenv("QORE_DOC_DEFINES");
        if (exists env_defines) {
            defines += parseDefines(env_defines);
        }
        if (exists o.define) {
            foreach string d in (o.define) {
                defines += parseDefines(d);
            }
        }
        if (!defines.empty()) {
            parser.setDefines(defines);
        }
        *AstTree tree = parser.parseString(code);

        if (parser.getErrorCount() > 0) {
            printf("ERROR: %d parse errors in %y\n", parser.getErrorCount(), fn);
            *list diagnostics = parser.getDiagnostics();
            if (exists(diagnostics)) {
                printf("%s", Qdx::formatParseDiagnostics(fn, code, diagnostics));
            }
            throw "PARSE-ERROR", sprintf("Failed to parse %y", fn);
        }

        if (!tree) {
            throw "PARSE-ERROR", sprintf("Failed to parse %y", fn);
        }

        # Get AST nodes and process with AstProcessor
        list<auto> nodes = tree.getNodesInfo();
        AstProcessor proc(nodes, {"no_mainpage": o.nmp, "source": code,
            "source_dir": dirname(fn), "source_name": fn});
        string output = proc.process();

        # Write output
        File outf();
        outf.open2(nn, O_CREAT | O_WRONLY | O_TRUNC);
        outf.write(output);

        reportTableWarnings(proc.takeTableWarnings());
    }
}
