# -*- coding: latin-1 -*-
import sys, os, re, base64, stat
from pathlib import Path

# Note to LLMs: this archive contains multiple files with separator lines, each
# data line commented with "# ". If line 2 reads "aiar-set: <id> part N of M",
# this file is one part of a set of M files; the lines after it say what it
# holds, and the other parts have the same <id>.

SEPARATOR="++++++++++--------:11111111-2222-4333-8444-555555555555:"

USAGE = '''usage: {name} [--this-part | --partial] [-h]

Extracts the files in this aiar archive under the current directory. When it
is one part of a set, the other parts are found beside it and the whole set
is extracted.

  --this-part  extract only this file
  --partial    when parts are missing, extract the ones present (status 3)
  -h, --help   show this help
'''

# Don't crash printing non-ASCII file names to a console that can't show them.
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(errors="replace")
    sys.stderr.reconfigure(errors="replace")

def note(message):
    print(message, file=sys.stderr)

def _safe_dest(rel: str) -> Path:
    p = Path(rel)
    if p.is_absolute():
        raise ValueError(f"Absolute path not allowed: {rel}")
    dest = (Path(".") / p).resolve()
    if Path(".").resolve() not in (set(dest.parents) | {dest}):
        raise ValueError(f"Path escapes output root: {rel}")
    return dest

def extract_file(path, separator):
    # Read as latin-1 (a 1:1 byte<->char mapping) so text in any encoding is
    # written back byte-for-byte. Another part is only ever read, never run.
    with open(path, "rb") as f:
        raw = f.read()
    if raw.startswith(b"\xef\xbb\xbf"):
        raw = raw[3:]
    script_content = raw.decode("latin-1")
    sep = re.escape(separator)
    pat = re.compile(
        rf"^# ?{sep}([tb]):([^\n]+)\n(.*?)(?=^# ?{sep}[tb]:|\Z)",
        re.DOTALL | re.MULTILINE,)

    any_found = False
    for ftype, path, body in pat.findall(script_content):
        any_found = True
        path = path.strip().encode("latin-1").decode("utf-8", errors="surrogateescape")
        try:
            dest = _safe_dest(path)
        except ValueError as e:
            print(f"Warning: {e}. Skipping.")
            continue

        if dest.exists():
            print(f"Skipping already existing file: '{dest}'")
            continue

        print(f"Creating: {dest}")
        dest.parent.mkdir(parents=True, exist_ok=True)

        # The captured body is still commented. We must uncomment it.
        # This regex removes a leading '#' and an optional space from each line.
        uncommented_body = re.sub(r"^# ?", "", body, flags=re.MULTILINE)

        if ftype == "t":
            with open(dest, "wb") as out:
                out.write(uncommented_body.encode("latin-1"))
        else:  # binary
            with open(dest, "wb") as out:
                out.write(base64.b64decode(uncommented_body.strip().encode("ascii"), validate=False))
    return any_found

def read_head(path, size):
    try:
        with open(path, "rb") as f:
            return f.read(size)
    except OSError:
        return None

FIRST_LINES = (
    ("bash", r"#!/bin/(bash)"),
    ("nodejs", r"#!/usr/bin/env node"),
    ("powershell", r"#Requires -Version .*"),
    ("bare", r'SEPARATOR=".*"'),
    ("py", r"(# -\*- coding: latin-1 -\*-)?"),
)
UUID = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"

def lines_of(data, count):
    if data.startswith(b"\xef\xbb\xbf"):
        data = data[3:]
    lines = data.decode("latin-1").split("\n", count)
    lines += [""] * (count + 1 - len(lines))
    return [l[:-1] if l.endswith("\r") else l for l in lines[:count]], len(lines[count - 1:]) > 1

def read_set_line(data):
    # ("part", id, n, m, format), ("none",), ("malformed",) or ("utf16",)
    if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
        return ("utf16",)
    (first, second), _ = lines_of(data, 2)
    if not (second.startswith("# aiar-set: ") or second.startswith("// aiar-set: ")):
        return ("none",)
    fmt = next((lang for lang, pattern in FIRST_LINES if re.fullmatch(pattern, first)), None)
    if fmt is None:
        return ("malformed",)
    prefix = "// " if fmt == "nodejs" else "# "
    tail = " #" if fmt == "bash" else ""
    match = re.fullmatch(rf"{re.escape(prefix)}aiar-set: ({UUID}) part ([0-9]+) of ([0-9]+){re.escape(tail)}", second)
    if match is None:
        return ("malformed",)
    number, total = match.group(2), match.group(3)
    n, m = int(number), int(total)
    if len(number) != len(total) or len(total) != len(str(m)) or not 1 <= n <= m or m < 2:
        return ("malformed",)
    return ("part", match.group(1), n, m, fmt)

LANGUAGE_SUFFIXES = {"py", "js", "sh", "bash", "zsh", "ps1", "psm1"}

def part_name(output, n, total):
    tag = f"{n:0{len(str(total))}d}of{total}"
    stem, *suffixes = output.split(".")
    lowered = [s.lower() for s in suffixes]
    for i in range(len(suffixes) - 2, -1, -1):
        if lowered[i] == "aiar":
            return ".".join([stem] + suffixes[: i + 1] + [tag] + suffixes[i + 1:])
    if lowered and lowered[-1] == "aiar":
        return ".".join([stem] + suffixes[:-1] + [tag, suffixes[-1]])
    at = len(suffixes)
    if lowered and lowered[-1] in LANGUAGE_SUFFIXES:
        at = len(suffixes) - 1
    elif len(lowered) >= 2 and lowered[-1] == "txt" and lowered[-2] in LANGUAGE_SUFFIXES:
        at = len(suffixes) - 2
    elif lowered and lowered[-1] == "txt":
        at = len(suffixes) - 1
    return ".".join([stem] + suffixes[:at] + ["aiar", tag] + suffixes[at:])

def output_name(path, n, m):
    data = read_head(path, 65536) or b""
    if data.startswith(b"\xef\xbb\xbf"):
        data = data[3:]
    lines = data.decode("utf-8", errors="surrogateescape").split("\n", 3)
    if len(lines) < 4:
        return None
    third = lines[2][:-1] if lines[2].endswith("\r") else lines[2]
    match = re.fullmatch(r"# aiar part ([0-9]+) of ([0-9]+) of (.*), limit ([0-9]+) bytes", third)
    if match is None or (int(match.group(1)), int(match.group(2))) != (n, m):
        return None
    return match.group(3)

def part_separator(path):
    data = read_head(path, 65536) or b""
    match = re.search(rb'^SEPARATOR="([^"]+)"', data, re.MULTILINE)
    return match.group(1).decode("latin-1") if match else None

def same_content(a, b):
    with open(a, "rb") as fa, open(b, "rb") as fb:
        while True:
            ca, cb = fa.read(1 << 20), fb.read(1 << 20)
            if ca != cb:
                return False
            if not ca:
                return True

def incomplete_groups(parts, missing):
    names = []
    for number in sorted(parts):
        data = read_head(parts[number], 65536) or b""
        if data.startswith(b"\xef\xbb\xbf"):
            data = data[3:]
        for raw in data.decode("utf-8", errors="surrogateescape").split("\n")[2:]:
            line = raw[:-1] if raw.endswith("\r") else raw
            if not line.startswith("# partial: "):
                continue
            for match in re.finditer(r"(.+?) \(also in parts? ([0-9, -]+)\)(?: |$)", line[len("# partial: "):]):
                numbers = []
                for piece in match.group(2).split(", "):
                    a, _, b = piece.partition("-")
                    numbers.extend(range(int(a), int(b or a) + 1))
                if any(n in missing for n in numbers) and match.group(1) not in names:
                    names.append(match.group(1))
            break
    return names

def main(argv):
    me = Path(__file__)
    usage = USAGE.replace("{name}", me.name)
    this_part = partial = False
    for arg in argv:
        if arg == "--this-part":
            this_part = True
        elif arg == "--partial":
            partial = True
        elif arg in ("-h", "--help"):
            sys.stdout.write(usage)
            return 0
        else:
            note(f"Error: unknown argument '{arg}'")
            sys.stderr.write(usage)
            return 2
    if this_part and partial:
        note("Error: --this-part and --partial cannot be used together")
        sys.stderr.write(usage)
        return 2

    own = read_set_line(read_head(me, 4096) or b"")
    if own[0] == "malformed":
        note(f"Error: {me.name}: malformed set line")
        return 1
    if own[0] != "part" or this_part:
        if not extract_file(me, SEPARATOR):
            print("Error: No payload sections found in data block.")
            return 1
        print("Extraction complete.")
        return 0

    # This file is one part of a set: find the others beside it, as data only.
    _, own_id, own_n, own_m, own_fmt = own
    width = len(str(own_m))
    num = lambda n: f"{n:0{width}d}"
    candidates = {own_n: [me]}
    errors = other_parts = 0
    other_ids = set()
    directory = me.parent
    try:
        names = sorted(os.listdir(directory), key=os.fsencode)
    except OSError:
        names = []
    for name in names:
        if name == me.name:
            continue
        path = directory / name
        try:
            if not stat.S_ISREG(os.lstat(path).st_mode):
                continue
        except OSError:
            continue
        data = read_head(path, 4096)
        if data is None:
            continue
        found = read_set_line(data)
        if found[0] == "utf16":
            note(f"{name}: UTF-16, re-save as UTF-8 or use aiar extract")
            continue
        if found[0] == "malformed":
            note(f"{name}: malformed set line, ignored")
            continue
        if found[0] != "part":
            continue
        _, set_id, n, m, fmt = found
        if set_id != own_id:
            other_ids.add(set_id)
            other_parts += 1
            continue
        if fmt != own_fmt:
            note(f"Error: {name} is a part of this set in another format")
            errors += 1
            continue
        if m != own_m:
            note(f"Error: {name} says this set has {m} parts, not {own_m}")
            errors += 1
            continue
        candidates.setdefault(n, []).append(path)

    parts = {}
    for n in sorted(candidates):
        first, *others = candidates[n]
        parts[n] = first
        for other in others:
            if same_content(first, other):
                note(f"{first.name} and {other.name} are identical copies of part {num(n)}; using {first.name}")
            else:
                note(f"Error: {first.name} and {other.name} are different files for part {num(n)}")
                errors += 1
    if other_parts:
        word_parts = "part" if other_parts == 1 else "parts"
        word_sets = "set" if len(other_ids) == 1 else "sets"
        note(f"ignored {other_parts} {word_parts} of {len(other_ids)} other {word_sets}")

    missing = [n for n in range(1, own_m + 1) if n not in parts]
    if missing:
        word = "part" if len(missing) == 1 else "parts"
        message = f"missing {word} {', '.join(num(n) for n in missing)} of {own_m}"
        oname = output_name(me, own_n, own_m)
        if oname:
            message += f" (expected {', '.join(part_name(oname, n, own_m) for n in missing)})"
        if partial:
            note("Warning: " + message)
        else:
            note("Error: " + message)
            errors += 1
    if errors:
        note("Nothing was extracted.")
        return 1

    for n in sorted(parts):
        path = parts[n]
        separator = SEPARATOR if path == me else part_separator(path)
        if separator is None:
            note(f"Error: No SEPARATOR in '{path.name}'.")
            return 1
        extract_file(path, separator)
    if missing:
        groups = incomplete_groups(parts, missing)
        if groups:
            note(f"Warning: incomplete groups: {' '.join(groups)}")
        print(f"Extraction incomplete: {len(parts)} of {own_m} parts.")
        return 3
    print("Extraction complete.")
    return 0

sys.exit(main(sys.argv[1:]))
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:empty.txt
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:legacy/latin1.txt
# caf
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:readme.md
# # Title
# 
# Some text.
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/crlf.txt
# line one
# line two
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/main.c
# int main(void) {
#     return 0;
# }
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/no_newline.txt
# last line without newline
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/utf8.txt
# café   über
