"""Align protein sequences with Clustal Omega and measure how conserved they are.

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 itertools import combinations
from pathlib import Path

import proteiniq_job

AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWYBZXUO")


def read_fasta(fasta: Path) -> list[tuple[str, str]]:
    records, name = [], None
    for line in fasta.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line.startswith(">"):
            name = line[1:].split()[0] if line[1:].strip() else ""
            records.append([name, ""])
        elif line:
            if name is None:
                raise ValueError("Start the file with a >name header line.")
            records[-1][1] += line.upper()
    names = [name for name, _ in records]
    if len(records) < 2:
        raise ValueError("Clustal Omega needs at least 2 sequences.")
    if "" in names or len(set(names)) != len(names):
        raise ValueError("Give every sequence its own unique name after the >.")
    for name, sequence in records:
        unknown = set(sequence) - AMINO_ACIDS
        if not sequence or unknown:
            raise ValueError(f"{name}: not a protein sequence; unexpected letters {sorted(unknown)}")
    return [(name, sequence) for name, sequence in records]


def make_request(fasta: Path) -> dict:
    records = read_fasta(fasta)
    content = "\n".join(f">{name}\n{sequence}" for name, sequence in records)
    sequences = proteiniq_job.text_input("sequences", "msa", "fasta", content, fasta.stem)
    settings = {"sequence_type": "Protein", "output_format": "clustal", "iterations": 1,
                "use_full_matrix": False, "output_order": "input-order", "dealign": False,
                "output_distance_matrix": False, "output_guide_tree": False}
    return {"tool": "clustal-omega", "input": {"inputs": [sequences]}, "settings": settings}


def read_clustal(path: Path) -> dict[str, str]:
    """Join the blocks of a Clustal file into one aligned row per sequence."""
    lines = path.read_text(encoding="utf-8").splitlines()
    if not lines or not lines[0].startswith("CLUSTAL"):
        raise ValueError(f"{path.name} is not a Clustal alignment")
    rows: dict[str, str] = {}
    for line in lines[1:]:
        # Blank lines separate blocks; lines starting with a space hold the * : . track.
        if not line.strip() or line[0].isspace():
            continue
        name, segment, *_ = line.split()
        rows[name] = rows.get(name, "") + segment
    if len({len(row) for row in rows.values()}) != 1:
        raise ValueError(f"Rows in {path.name} have different lengths")
    return rows


def percent_identity(a: str, b: str) -> float:
    """Identical residues over columns where neither sequence has a gap."""
    pairs = [(x, y) for x, y in zip(a, b) if x != "-" and y != "-"]
    return 100 * sum(x == y for x, y in pairs) / len(pairs)


def columns(rows: dict[str, str], reference: str) -> list[dict]:
    """One record per column, numbered by the reference sequence's own residues."""
    number, table = 0, []
    for index, residues in enumerate(zip(*rows.values()), 1):
        if rows[reference][index - 1] != "-":
            number += 1
        table.append({
            "column": index,
            "reference_residue": number if rows[reference][index - 1] != "-" else None,
            "residues": "".join(residues),
            "identical": "-" not in residues and len(set(residues)) == 1,
        })
    return table


def conserved_blocks(table: list[dict], minimum: int = 10) -> list[tuple[int, int]]:
    """Runs of at least `minimum` identical columns, as (first, last) column numbers."""
    blocks, start = [], None
    for record in table + [{"column": len(table) + 1, "identical": False}]:
        if record["identical"] and start is None:
            start = record["column"]
        elif not record["identical"] and start is not None:
            if record["column"] - start >= minimum:
                blocks.append((start, record["column"] - 1))
            start = None
    return blocks


def report(result: dict, output: Path, positions: list[int] = ()) -> None:
    (alignment,) = proteiniq_job.output_files(output, r"\.aln$")
    rows = read_clustal(alignment)
    names = list(rows)
    reference = names[0]
    table = columns(rows, reference)
    with open(output / "conservation.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["column", f"{reference}_residue", *names, "identical"])
        for record in table:
            writer.writerow([record["column"], record["reference_residue"] or "",
                             *record["residues"], record["identical"]])
    identical = sum(record["identical"] for record in table)
    gapped = sum("-" in record["residues"] for record in table)
    print(f"{len(names)} sequences, {len(table)} columns, {gapped} with gaps")
    print(f"Identical in every sequence: {identical} columns ({100 * identical / len(table):.1f}%)")
    print("Pairwise identity:")
    for a, b in combinations(names, 2):
        print(f"  {a} vs {b}: {percent_identity(rows[a], rows[b]):.1f}%")
    sequence = rows[reference]
    print(f"Conserved blocks of 10+ columns, numbered by {reference}:")
    for first, last in conserved_blocks(table):
        start, end = table[first - 1]["reference_residue"], table[last - 1]["reference_residue"]
        print(f"  {start}-{end} {sequence[first - 1:last]}")
    by_residue = {record["reference_residue"]: record for record in table}
    for position in positions:
        record = by_residue.get(position)
        if record is None:
            print(f"  {reference} has no residue {position}")
            continue
        state = "identical" if record["identical"] else "varies"
        print(f"{reference} {sequence[record['column'] - 1]}{position}: "
              f"{' '.join(record['residues'])} ({state})")
    print(f"Per-column table: {output / 'conservation.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "clustal-omega-output")
    arguments.add_argument("--sequences", type=Path, help="FASTA file with 2 or more protein sequences.")
    arguments.add_argument("--positions", type=lambda text: [int(n) for n in text.split(",")], default=[],
                           help="Comma-separated residue numbers in the first sequence to report.")
    args = arguments.parse_args()
    if not args.resume and args.sequences is None:
        arguments.error("--sequences is required for a new run.")
    proteiniq_job.main(args, lambda: make_request(args.sequences),
                       lambda result, output: report(result, output, args.positions))
