import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from Bio.SeqUtils import gc_fraction

INPUT_FILE = "ls_orchid.fasta"
MOTIFS = ["ATG", "TATA", "GAATTC"]


def find_motif_positions(seq_str, motif):
    positions = []
    start = 0
    seq_str = seq_str.upper()
    while True:
        idx = seq_str.find(motif, start)
        if idx == -1:
            break
        positions.append(idx)
        start = idx + 1  # +1 so overlapping motifs like TATATA are not skipped
    return positions


def translate_6_frames(seq):
    frames = {}
    rev_comp = seq.reverse_complement()

    for offset in range(3):
        # trim trailing 1-2 bases so Biopython does not warn about partial codons
        fwd = seq[offset:]
        frames[offset + 1] = fwd[:len(fwd) - len(fwd) % 3].translate()

        rev = rev_comp[offset:]
        frames[offset + 4] = rev[:len(rev) - len(rev) % 3].translate()

    return frames


def get_longest_orf(frames):
    best = 0
    for prot in frames.values():
        for part in str(prot).split("*"):
            m_idx = part.find("M")
            if m_idx != -1:
                best = max(best, len(part) - m_idx)
    return best


def balance_rating(seq):
    # Criterion A: smallest difference between max and min nucleotide percentage (A, C, G, T)
    s = str(seq).upper()
    counts = [s.count(b) for b in ("A", "C", "G", "T")]
    total = sum(counts)
    pcts = [c / total * 100 for c in counts]
    diff = max(pcts) - min(pcts)
    score = 100 - diff  # closer to 100 means more balanced
    return score, diff


# Criterion B (most interesting sequence):
# Gives points for motifs (ATG=1, TATA=2, GAATTC=5 since EcoRI sites are rarer),
# longest open reading frame across all 6 frames (0.25 per amino acid), and GC%
# close to 50% (up to 10 pts), while subtracting 2 pts per ambiguous 'N' base.
def scoring(record, motifs_found, frames):
    s = str(record.seq).upper()
    gc_pct = gc_fraction(record.seq) * 100

    motif_score = (
        len(motifs_found["ATG"]) * 1
        + len(motifs_found["TATA"]) * 2
        + len(motifs_found["GAATTC"]) * 5
    )
    orf_score = get_longest_orf(frames) * 0.25
    gc_score = 10 * (1 - abs(gc_pct - 50) / 50)
    n_penalty = s.count("N") * 2

    return round(motif_score + orf_score + gc_score - n_penalty, 2)


def make_charts(records):
    first30 = records[:30]
    seqs = [str(r.seq).upper() for r in first30]
    # shorten NCBI IDs like gi|2765658|emb|Z78533.1|CIZ78533 to Z78533.1 for readable axis labels
    labels = [r.id.split("|")[3] if len(r.id.split("|")) >= 4 else r.id for r in first30]
    max_len = max(len(s) for s in seqs)

    # Chart 1: stacked bar chart of nucleotide distribution
    a = np.array([s.count("A") for s in seqs])
    c = np.array([s.count("C") for s in seqs])
    g = np.array([s.count("G") for s in seqs])
    t = np.array([s.count("T") for s in seqs])
    n = np.array([s.count("N") for s in seqs])

    x = np.arange(len(first30))
    plt.figure(figsize=(13, 6))
    plt.bar(x, a, label="A", color="tab:green")
    plt.bar(x, c, bottom=a, label="C", color="tab:blue")
    plt.bar(x, g, bottom=a + c, label="G", color="tab:orange")
    plt.bar(x, t, bottom=a + c + g, label="T", color="tab:red")
    if np.any(n > 0):
        plt.bar(x, n, bottom=a + c + g + t, label="N", color="gray")

    plt.title("Nucleotide Distribution (First 30 Sequences)")
    plt.xlabel("Sequence ID")
    plt.ylabel("Count")
    plt.xticks(x, labels, rotation=60, ha="right", fontsize=8)
    plt.ylim(0, max_len * 1.12)
    plt.legend(loc="upper center", ncol=5)
    plt.tight_layout()
    plt.savefig("chart1_nucleotide_distribution.png", dpi=150)
    plt.close()

    # Chart 2: heatmap of nucleotide type by position
    # 0=A, 1=C, 2=G, 3=T, 4=N, 5=no base (shorter sequence)
    code_map = {"A": 0, "C": 1, "G": 2, "T": 3, "N": 4}
    grid = np.full((len(first30), max_len), 5)
    for row, s in enumerate(seqs):
        for col, base in enumerate(s):
            grid[row, col] = code_map.get(base, 4)

    cmap = ListedColormap(["tab:green", "tab:blue", "tab:orange", "tab:red", "gray", "white"])
    plt.figure(figsize=(14, 7))
    im = plt.imshow(grid, aspect="auto", cmap=cmap, vmin=-0.5, vmax=5.5, interpolation="nearest")
    plt.title("Nucleotide Type by Position (First 30 Sequences)")
    plt.xlabel("Position")
    plt.ylabel("Sequence")
    plt.yticks(np.arange(len(first30)), labels, fontsize=7)
    cbar = plt.colorbar(im, ticks=[0, 1, 2, 3, 4, 5])
    cbar.ax.set_yticklabels(["A", "C", "G", "T", "N", "None"])
    plt.tight_layout()
    plt.savefig("chart2_nucleotide_heatmap.png", dpi=150)
    plt.close()

    # Chart 3: line plot of % GC at each position across the 30 sequences
    gc_by_pos = []
    for pos in range(max_len):
        gc_cnt = 0
        valid_cnt = 0
        for s in seqs:
            if pos < len(s) and s[pos] in ("A", "C", "G", "T"):
                valid_cnt += 1
                if s[pos] in ("G", "C"):
                    gc_cnt += 1
        gc_by_pos.append((gc_cnt / valid_cnt) * 100 if valid_cnt > 0 else np.nan)

    plt.figure(figsize=(13, 5))
    plt.plot(range(1, max_len + 1), gc_by_pos, linewidth=1.0, color="tab:blue")
    plt.title("GC Content (%) by Position (First 30 Sequences)")
    plt.xlabel("Position")
    plt.ylabel("GC (%)")
    plt.ylim(0, 105)
    plt.grid(alpha=0.3)
    plt.tight_layout()
    plt.savefig("chart3_gc_by_position.png", dpi=150)
    plt.close()


def main():
    records = list(SeqIO.parse(INPUT_FILE, "fasta"))
    print(f"Loaded {len(records)} sequences from {INPUT_FILE}\n")

    rows = []
    scores_a = []
    scores_b = []

    for rec in records:
        seq_str = str(rec.seq).upper()
        motifs_found = {m: find_motif_positions(seq_str, m) for m in MOTIFS}
        frames = translate_6_frames(rec.seq)

        print(f"Loaded sequence with id {rec.id}:")
        print(seq_str)
        print("Motifs found:")
        for m in MOTIFS:
            print(f"{m}:{motifs_found[m]}")
        print("Translation:")
        for f_num in range(1, 7):
            print(f"Frame {f_num}:{frames[f_num]}")
        print()

        gc_pct = gc_fraction(rec.seq) * 100
        rows.append({
            "sequence_id": rec.id,
            "A_count": seq_str.count("A"),
            "C_count": seq_str.count("C"),
            "G_count": seq_str.count("G"),
            "T_count": seq_str.count("T"),
            "N_count": seq_str.count("N"),
            "GC_percent": round(gc_pct, 2),
            "ATG_positions": str(motifs_found["ATG"]),
            "TATA_positions": str(motifs_found["TATA"]),
            "GAATTC_positions": str(motifs_found["GAATTC"]),
            "rev_comp_first_10": str(rec.seq.reverse_complement()[:10]),
            "frame1_len": len(frames[1]),
            "frame2_len": len(frames[2]),
            "frame3_len": len(frames[3]),
            "frame4_len": len(frames[4]),
            "frame5_len": len(frames[5]),
            "frame6_len": len(frames[6]),
        })

        b_score, diff = balance_rating(rec.seq)
        scores_a.append((b_score, diff, rec))

        i_score = scoring(rec, motifs_found, frames)
        scores_b.append((i_score, rec))

    # save charts for first 30 sequences
    make_charts(records)
    print("Saved charts: chart1_nucleotide_distribution.png, chart2_nucleotide_heatmap.png, chart3_gc_by_position.png")

    # save CSV report
    df = pd.DataFrame(rows)
    df.to_csv("orchid_report.csv", index=False)
    print(f"Saved CSV report to orchid_report.csv ({len(df)} rows)")

    # rank TOP 3 for both criteria
    scores_a.sort(key=lambda x: x[0], reverse=True)
    top3_a = []
    print("\nTOP 3 - Criterion A (most balanced):")
    for rank, (sc, diff, rec) in enumerate(scores_a[:3], 1):
        print(f"{rank}. {rec.id} - score: {sc:.2f} (max-min diff: {diff:.2f}%)")
        top3_a.append(SeqRecord(rec.seq, id=rec.id, description=f"{rec.description} | score={sc:.2f}"))
    SeqIO.write(top3_a, "criterion_a.fasta", "fasta")

    scores_b.sort(key=lambda x: x[0], reverse=True)
    top3_b = []
    print("\nTOP 3 - Criterion B (most interesting):")
    for rank, (sc, rec) in enumerate(scores_b[:3], 1):
        print(f"{rank}. {rec.id} - score: {sc:.2f}")
        top3_b.append(SeqRecord(rec.seq, id=rec.id, description=f"{rec.description} | score={sc:.2f}"))
    SeqIO.write(top3_b, "criterion_b.fasta", "fasta")
    print("\nSaved criterion_a.fasta and criterion_b.fasta")


if __name__ == "__main__":
    main()
