import json
import random
import sys
import textwrap
from datetime import datetime

from Bio.Seq import Seq
from Bio.SeqUtils import gc_fraction

# ANSI terminal colors
RESET = "\033[0m"
GREEN = "\033[92m"   # A
RED = "\033[91m"     # T
YELLOW = "\033[93m"  # G
BLUE = "\033[94m"    # C
PURPLE = "\033[95m"  # name

COLORS = {"A": GREEN, "T": RED, "G": YELLOW, "C": BLUE}

LOGO = r"""
  ____  _       ____        _   _
 | __ )(_) ___ |  _ \ _   _| |_| |__   ___  _ __
 |  _ \| |/ _ \| |_) | | | | __| '_ \ / _ \| '_ \
 | |_) | | (_) |  __/| |_| | |_| | | | (_) | | | |
 |____/|_|\___/|_|    \__, |\__|_| |_|\___/|_| |_|
                      |___/
"""


def show_progress(step, total):
    bar_len = 30
    filled = int(bar_len * step / total)
    bar = "#" * filled + "-" * (bar_len - filled)
    pct = (step / total) * 100
    sys.stdout.write(f"\rGenerating: [{bar}] {pct:5.1f}%")
    sys.stdout.flush()
    if step == total:
        print()


def generate_dna(length, target_gc=None):
    bases = []
    update_every = max(1, length // 20)

    if target_gc is not None:
        # pick a GC count close to target (within +-5%, usually within +-1.5%)
        chosen_gc = target_gc + random.uniform(-1.5, 1.5)
        chosen_gc = max(target_gc - 5, min(target_gc + 5, chosen_gc))
        gc_count = round(length * chosen_gc / 100)
        if abs((gc_count / length) * 100 - target_gc) > 5:
            gc_count = round(length * target_gc / 100)
        at_count = length - gc_count

        for i in range(gc_count):
            bases.append(random.choice(["G", "C"]))
            if (i + 1) % update_every == 0 or (i + 1) == gc_count:
                show_progress(i + 1, length)
        for j in range(at_count):
            bases.append(random.choice(["A", "T"]))
            done = gc_count + j + 1
            if done % update_every == 0 or done == length:
                show_progress(done, length)

        random.shuffle(bases)
    else:
        for i in range(length):
            bases.append(random.choice(["A", "C", "G", "T"]))
            if (i + 1) % update_every == 0 or (i + 1) == length:
                show_progress(i + 1, length)

    return Seq("".join(bases))


def get_stats(dna_seq):
    n = len(dna_seq)
    a = dna_seq.count("A")
    c = dna_seq.count("C")
    g = dna_seq.count("G")
    t = dna_seq.count("T")

    gc_pct = gc_fraction(dna_seq) * 100
    cg_at = (c + g) / (a + t) if (a + t) > 0 else None

    return {
        "A": (a / n) * 100,
        "C": (c / n) * 100,
        "G": (g / n) * 100,
        "T": (t / n) * 100,
        "GC": gc_pct,
        "CG_AT": cg_at,
    }


def find_long_repeats(dna_str, min_len=5):
    repeats = []
    if not dna_str:
        return repeats
    run_char = dna_str[0]
    run_len = 1
    for ch in dna_str[1:]:
        if ch == run_char:
            run_len += 1
        else:
            if run_len >= min_len:
                repeats.append(run_char * run_len)
            run_char = ch
            run_len = 1
    if run_len >= min_len:
        repeats.append(run_char * run_len)
    return repeats


def check_quality(dna_seq, stats):
    warnings = []
    if stats["GC"] < 30 or stats["GC"] > 70:
        warnings.append(f"Extreme GC content: {stats['GC']:.2f}% (outside 30-70% range)")

    repeats = find_long_repeats(str(dna_seq), min_len=5)
    if repeats:
        shown = ", ".join(repeats[:5])
        warnings.append(f"Found {len(repeats)} repeat(s) longer than 4: {shown}")

    return warnings


def color_sequence(dna_seq, name, pos):
    s = str(dna_seq)
    left = "".join(COLORS[b] + b + RESET for b in s[:pos])
    right = "".join(COLORS[b] + b + RESET for b in s[pos:])
    colored_name = PURPLE + name + RESET
    return left + colored_name + right


def main():
    print(LOGO)

    length = int(input("Input sequence length: "))
    while length <= 0:
        length = int(input("Length must be > 0. Input sequence length: "))

    seq_id = input("Input sequence ID: ").strip()
    description = input("Input sequence description: ").strip()
    name = input("Input name: ").strip()

    # optional target GC%
    gc_input = input("Target GC content % (40-60, press Enter for random): ").strip()
    target_gc = None
    while gc_input:
        try:
            val = float(gc_input)
            if 40 <= val <= 60:
                target_gc = val
                break
            gc_input = input("Enter a number between 40 and 60 (or Enter to skip): ").strip()
        except ValueError:
            gc_input = input("Invalid number. Enter 40-60 (or Enter to skip): ").strip()

    count_input = input("How many sequences to generate? (default 1): ").strip()
    num_seqs = int(count_input) if count_input else 1
    if num_seqs < 1:
        num_seqs = 1

    export_fmt = input("Export format (fasta/json, default fasta): ").strip().lower()
    if export_fmt not in ("fasta", "json"):
        export_fmt = "fasta"

    wrap_width = 60
    if export_fmt == "fasta":
        wrap_input = input("FASTA line wrapping width (60 or 80, default 60): ").strip()
        if wrap_input in ("60", "80"):
            wrap_width = int(wrap_input)

    now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    all_entries = []

    for i in range(1, num_seqs + 1):
        current_id = seq_id if num_seqs == 1 else f"{seq_id}_{i}"
        print(f"\nGenerating {current_id} ({i}/{num_seqs})...")

        # repeat generation if the user wants to fix QC warnings
        while True:
            dna_seq = generate_dna(length, target_gc)
            stats = get_stats(dna_seq)
            warnings = check_quality(dna_seq, stats)
            if warnings:
                print("Quality warnings:")
                for w in warnings:
                    print(" -", w)
                again = input("Regenerate this sequence? (y/n): ").strip().lower()
                if again == "y":
                    continue
            break

        # insert name after stats so it does not skew nucleotide counts or length
        insert_pos = random.randint(0, len(dna_seq))
        seq_with_name = str(dna_seq[:insert_pos]) + name + str(dna_seq[insert_pos:])

        print("Sequence:", color_sequence(dna_seq, name, insert_pos))

        print("Sequence statistics:")
        print(f"A: {stats['A']:.1f}%")
        print(f"C: {stats['C']:.1f}%")
        print(f"G: {stats['G']:.1f}%")
        print(f"T: {stats['T']:.1f}%")
        if stats["CG_AT"] is not None:
            print(f"CG/AT: {stats['CG_AT']:.2f}")
        else:
            print("CG/AT: N/A (no A or T)")
        print(f"Inserted name position: {insert_pos}")

        if target_gc is not None:
            diff = stats["GC"] - target_gc
            print(f"GC content: {stats['GC']:.2f}% (target: {target_gc:.1f}%, diff: {diff:+.2f}%)")

        all_entries.append({
            "id": current_id,
            "description": description,
            "dna_length": length,
            "inserted_name": name,
            "inserted_name_position": insert_pos,
            "stats": {
                "A": round(stats["A"], 2),
                "C": round(stats["C"], 2),
                "G": round(stats["G"], 2),
                "T": round(stats["T"], 2),
                "GC": round(stats["GC"], 2),
                "CG_AT": round(stats["CG_AT"], 3) if stats["CG_AT"] is not None else None,
            },
            "warnings": warnings,
            "sequence": seq_with_name,
        })

    out_file = f"{seq_id}.{export_fmt}"
    if export_fmt == "fasta":
        with open(out_file, "w", encoding="utf-8") as f:
            f.write(f"##Generated: {now_str} | Tool: Python\n")
            for entry in all_entries:
                f.write(f">{entry['id']} {entry['description']}\n")
                f.write(textwrap.fill(entry["sequence"], width=wrap_width) + "\n")
    else:
        data = {
            "generated": now_str,
            "tool": "Python",
            "total_sequences": len(all_entries),
            "sequences": all_entries,
        }
        with open(out_file, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)

    print(f"\nSequence was saved to {out_file} file")

    # batch summary
    if num_seqs > 1:
        avg_a = sum(e["stats"]["A"] for e in all_entries) / num_seqs
        avg_c = sum(e["stats"]["C"] for e in all_entries) / num_seqs
        avg_g = sum(e["stats"]["G"] for e in all_entries) / num_seqs
        avg_t = sum(e["stats"]["T"] for e in all_entries) / num_seqs
        gc_vals = [e["stats"]["GC"] for e in all_entries]
        ratios = [e["stats"]["CG_AT"] for e in all_entries if e["stats"]["CG_AT"] is not None]

        print(f"\nSummary for all {num_seqs} sequences:")
        print(f"Total DNA length (without names): {length * num_seqs}")
        print(f"Avg A: {avg_a:.2f}%, C: {avg_c:.2f}%, G: {avg_g:.2f}%, T: {avg_t:.2f}%")
        print(f"GC%: avg {sum(gc_vals) / num_seqs:.2f}% (min {min(gc_vals):.2f}%, max {max(gc_vals):.2f}%)")
        if ratios:
            print(f"Avg CG/AT: {sum(ratios) / len(ratios):.2f}")


if __name__ == "__main__":
    main()
