"""Build a maximum likelihood tree with IQ-TREE and list its clades with support.

Quotes by default. Add --submit --max-credits N to run one job. Keep the output
folder to resume. Needs proteiniq_job.py from the same page in this folder.
"""
from __future__ import annotations

import csv
from pathlib import Path
import re

import proteiniq_job

FORMATS = {".fasta": "fasta", ".fa": "fasta", ".fas": "fasta"}


def check_alignment(path: Path) -> int:
    """Count the sequences and stop early if the rows are not aligned."""
    lengths, names = {}, []
    for line in path.read_text(encoding="utf-8").splitlines():
        if line.startswith(">"):
            names.append(line[1:].strip())
            lengths[names[-1]] = 0
        elif names:
            lengths[names[-1]] += len(line.strip())
    if len(names) < 4:
        raise ValueError("Ultrafast bootstrap needs at least 4 aligned sequences.")
    if len(set(names)) != len(names):
        raise ValueError("Sequence names must be unique.")
    if len(set(lengths.values())) != 1:
        raise ValueError("Sequences differ in length; align them first, for example with MAFFT.")
    return len(names)


def make_request(alignment: Path) -> dict:
    check_alignment(alignment)
    data = proteiniq_job.file_input(alignment, "alignment", "msa", FORMATS)
    settings = {"interface": "native", "sequence_type": "auto", "model": "AUTO",
                "bootstrap": 1000, "alrt": 1000, "seed": 12345, "custom_model": "",
                "custom_sequence_type": "", "native_options": "[]"}
    return {"tool": "iq-tree", "input": {"inputs": [data]}, "settings": settings}


def parse_newick(text: str) -> dict:
    """Read a Newick string into nested nodes with name, label, length and children."""
    position = 0

    def node() -> dict:
        nonlocal position
        children = []
        if text[position] == "(":
            position += 1
            children.append(node())
            while text[position] == ",":
                position += 1
                children.append(node())
            if text[position] != ")":
                raise ValueError(f"Expected ')' at character {position}")
            position += 1
        match = re.compile(r"([^:,();]*)(?::([^,();]+))?").match(text, position)
        position = match.end()
        name = match.group(1).strip()
        return {"name": "" if children else name, "label": name if children else "",
                "length": float(match.group(2)) if match.group(2) else None, "children": children}

    text = text.strip()
    tree = node()
    if text[position:] != ";":
        raise ValueError("Newick tree must end with ';'")
    return tree


def leaves(node: dict) -> frozenset[str]:
    if not node["children"]:
        return frozenset([node["name"]])
    return frozenset().union(*(leaves(child) for child in node["children"]))


def clades(tree: dict, outgroup: str) -> list[tuple[frozenset[str], str]]:
    """Every internal branch as the group it separates from the outgroup, with its support label."""
    taxa = leaves(tree)
    if outgroup not in taxa:
        raise ValueError(f"Outgroup {outgroup} is not in the tree")
    found, seen = [], set()

    def visit(node: dict) -> None:
        for child in node["children"]:
            if child["children"]:
                side = leaves(child)
                # An unrooted tree has no direction; take the side without the outgroup.
                group = side if outgroup not in side else taxa - side
                if 1 < len(group) < len(taxa) - 1 and group not in seen:
                    seen.add(group)
                    found.append((group, child["label"]))
                visit(child)

    visit(tree)
    return sorted(found, key=lambda item: (-len(item[0]), sorted(item[0])))


def draw(taxa: frozenset[str], groups: list[tuple[frozenset[str], str]], depth: int = 0) -> list[str]:
    """Indent nested clades so the tree reads from the root down."""
    lines, placed = [], set()
    for group, label in groups:
        if group <= taxa and group != taxa and not group & placed:
            inner = [(g, l) for g, l in groups if g < group]
            lines.append(f"{'  ' * depth}+ ({label or 'no support'})")
            lines += draw(group, inner, depth + 1)
            placed |= group
    lines += [f"{'  ' * depth}{name}" for name in sorted(taxa - placed)]
    return lines


def model_ranking(report: Path, count: int = 3) -> list[tuple[str, float, float, float]]:
    """The first rows of ModelFinder's BIC table: model, log-likelihood, BIC and BIC weight."""
    lines = report.read_text(encoding="utf-8").splitlines()
    start = next(i for i, line in enumerate(lines) if line.startswith("List of models sorted by BIC"))
    rows = []
    for line in lines[start + 3:]:
        fields = line.split()
        if len(fields) != 11:
            break
        rows.append((fields[0], float(fields[1]), float(fields[8]), float(fields[10])))
    return rows[:count]


def report(result: dict, output: Path, outgroup: str | None = None) -> None:
    summary = result["summary"]
    (treefile,) = proteiniq_job.output_files(output, r"\.treefile$")
    (iqtree,) = proteiniq_job.output_files(output, r"\.iqtree$")
    tree = parse_newick(treefile.read_text(encoding="utf-8"))
    taxa = leaves(tree)
    # Without an outgroup, follow IQ-TREE and put the first taxon at the root.
    first = tree
    while first["children"]:
        first = first["children"][0]
    outgroup = outgroup or first["name"]
    groups = clades(tree, outgroup)
    print(f"{summary['sequences']} sequences, {summary['sites']} sites, {summary['sequence_type']}")
    print(f"Best-fit model (BIC): {summary['model']}, log-likelihood {summary['log_likelihood']:.3f}")
    for model, log_likelihood, bic, weight in model_ranking(iqtree):
        print(f"  {model:<14} logL {log_likelihood:.3f}  BIC {bic:.3f}  weight {weight:.3g}")
    print(f"Clades with SH-aLRT/UFBoot support, rooted on {outgroup}:")
    for line in draw(taxa, groups):
        print(f"  {line}")
    with open(output / "clades.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["taxa", "size", "sh_alrt", "ufboot"])
        for group, label in groups:
            alrt, _, ufboot = label.partition("/")
            writer.writerow([" ".join(sorted(group)), len(group), alrt, ufboot])
    print(f"Clade table: {output / 'clades.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "iq-tree-output")
    arguments.add_argument("--alignment", type=Path, help="Aligned FASTA file with 4 or more sequences.")
    arguments.add_argument("--outgroup", help="Taxon to root the clade list on (default: the first taxon in the tree).")
    args = arguments.parse_args()
    if not args.resume and args.alignment is None:
        arguments.error("--alignment is required for a new run.")
    # IQ-TREE is billed by runtime: --max-credits also caps what the run may spend.
    proteiniq_job.main(args, lambda: make_request(args.alignment),
                       lambda result, output: report(result, output, args.outgroup), metered=True)
