#!/usr/bin/env python3
# collect_code.py
# Scan a directory tree, render a textual tree, and concatenate source files
# into a single output file (default: code.txt).
# This version avoids including itself, code.txt, code_update.txt, unpack_code.py,
# restored_project/restore_project and files that look like versioned backups.

import argparse
import os
import sys
import hashlib
from pathlib import Path
from datetime import datetime
import re

DEFAULT_OUT = "code.txt"
DEFAULT_EXCLUDE_DIRS = {".git", "__pycache__", "node_modules", ".venv", "venv", ".idea", ".pytest_cache", "restored_project", "restore_project"}
DEFAULT_EXTS = {
    "py", "html", "htm", "js", "jsx", "ts", "tsx", "css", "scss", "less",
    "json", "yaml", "yml", "md", "txt", "ps1", "bat", "sh", "ini", "cfg",
    "sql", "xml", "csv", "rst"
}
DEFAULT_MAX_SIZE = 20 * 1024 * 1024  # 20 MiB

_VERSIONED_RE = re.compile(r"\.v\d+(\.|$)", re.IGNORECASE)

def is_text_file(path: Path, blocksize: int = 512) -> bool:
    try:
        with path.open("rb") as f:
            block = f.read(blocksize)
            if not block:
                return True
            if b"\x00" in block:
                return False
            try:
                block.decode("utf-8")
                return True
            except Exception:
                try:
                    block.decode("latin-1")
                    return True
                except Exception:
                    return False
    except Exception:
        return False

def file_sha256(path: Path, chunk_size: int = 8192) -> str:
    h = hashlib.sha256()
    try:
        with path.open("rb") as f:
            while True:
                chunk = f.read(chunk_size)
                if not chunk:
                    break
                h.update(chunk)
        return h.hexdigest()
    except Exception:
        return ""

def human_size(n: int) -> str:
    for unit in ("B","KB","MB","GB","TB"):
        if n < 1024.0:
            return f"{n:.1f}{unit}"
        n /= 1024.0
    return f"{n:.1f}PB"

def is_versioned_filename(name: str) -> bool:
    return bool(_VERSIONED_RE.search(name))

def build_tree(root: Path, exclude_dirs: set):
    lines = []
    root = root.resolve()

    def _walk(dirpath: Path, prefix: str = ""):
        try:
            entries = sorted(list(dirpath.iterdir()), key=lambda p: (p.is_file(), p.name.lower()))
        except PermissionError:
            lines.append(prefix + "[permission denied] " + str(dirpath))
            return
        dirs = [e for e in entries if e.is_dir()]
        files = [e for e in entries if e.is_file()]

        for i, d in enumerate(dirs):
            name = d.name
            if name in exclude_dirs:
                connector = "└── " if (i == len(dirs)-1 and not files) else "├── "
                lines.append(prefix + connector + name + "/ [excluded]")
                continue
            connector = "└── " if (i == len(dirs)-1 and not files) else "├── "
            lines.append(prefix + connector + name + "/")
            new_prefix = prefix + ("    " if connector == "└── " else "│   ")
            _walk(d, new_prefix)

        for j, f in enumerate(files):
            connector = "└── " if j == len(files)-1 else "├── "
            try:
                st = f.stat()
                size = st.st_size
            except Exception:
                size = 0
            lines.append(prefix + connector + f.name + f" ({human_size(size)})")
    lines.append(str(root) + "/")
    _walk(root, "")
    return lines

def collect_and_write(root: Path, out_path: Path, include_exts: set, exclude_dirs: set, max_size: int, verbose: bool = True):
    root = root.resolve()
    out_path = out_path.resolve()
    tmp_path = out_path.with_suffix(out_path.suffix + ".tmp")
    now = datetime.utcnow().isoformat() + "Z"

    script_path = Path(__file__).resolve()
    skip_names = {script_path.name, out_path.name, "code_update.txt", "code.txt", "unpack_code.py", "restored_project", "restore_project"}

    tree_lines = build_tree(root, exclude_dirs)

    with tmp_path.open("w", encoding="utf-8", errors="replace") as out:
        out.write("# Collected code snapshot\n")
        out.write(f"# Root: {root}\n")
        out.write(f"# Generated: {now}\n")
        out.write(f"# Max included file size: {human_size(max_size)}\n")
        out.write("# Included extensions: " + ", ".join(sorted(include_exts)) + "\n")
        out.write("\n")
        out.write("## Directory tree\n\n")
        for l in tree_lines:
            out.write(l + "\n")
        out.write("\n")
        out.write("## Files content (selected extensions)\n\n")

        for dirpath, dirnames, filenames in os.walk(root):
            dirnames[:] = [d for d in dirnames if d not in exclude_dirs]
            rel_dir = os.path.relpath(dirpath, root)
            for fname in sorted(filenames):
                fpath = Path(dirpath) / fname
                rel_path = os.path.join(rel_dir, fname) if rel_dir != "." else fname

                if fname in skip_names:
                    if verbose:
                        print(f"Skipping reserved file: {rel_path}")
                    continue

                if is_versioned_filename(fname):
                    if verbose:
                        print(f"Skipping versioned file: {rel_path}")
                    continue

                ext = fpath.suffix.lower().lstrip(".")
                if fname.lower() == "dockerfile":
                    ext = "dockerfile"
                if ext not in include_exts:
                    continue

                try:
                    st = fpath.stat()
                    size = st.st_size
                    mtime = datetime.utcfromtimestamp(st.st_mtime).isoformat() + "Z"
                except Exception:
                    size = 0
                    mtime = "unknown"

                out.write("#" * 80 + "\n")
                out.write(f"# File: {rel_path}\n")
                out.write(f"# Absolute: {str(fpath.resolve())}\n")
                out.write(f"# Size: {size} bytes ({human_size(size)})\n")
                out.write(f"# Modified: {mtime}\n")
                sha = file_sha256(fpath)
                if sha:
                    out.write(f"# SHA256: {sha}\n")
                out.write("#" * 80 + "\n")

                if size > max_size:
                    out.write(f"# SKIPPED: file larger than {human_size(max_size)}\n\n")
                    if verbose:
                        print(f"Skipping large file: {rel_path} ({human_size(size)})")
                    continue

                if not is_text_file(fpath):
                    out.write("# SKIPPED: binary file (non-text)\n\n")
                    if verbose:
                        print(f"Skipping binary file: {rel_path}")
                    continue

                try:
                    with fpath.open("r", encoding="utf-8", errors="replace") as fh:
                        out.write(fh.read())
                        out.write("\n")
                except Exception as e:
                    out.write(f"# ERROR reading file: {e}\n\n")
                    if verbose:
                        print(f"Error reading {rel_path}: {e}")
        out.write("\n# End of collected code\n")

    try:
        tmp_path.replace(out_path)
    except Exception:
        tmp_path.rename(out_path)
    print(f"Wrote collected code to: {out_path}")

def parse_args():
    p = argparse.ArgumentParser(description="Collect code files and produce a single code.txt with a directory tree and file contents.")
    p.add_argument("-r", "--root", default=".", help="Root directory to scan (default: current dir).")
    p.add_argument("-o", "--out", default=DEFAULT_OUT, help=f"Output file (default: {DEFAULT_OUT}).")
    p.add_argument("--exts", default=",".join(sorted(DEFAULT_EXTS)), help="Comma-separated list of extensions to include (no dots).")
    p.add_argument("--exclude", default=",".join(sorted(DEFAULT_EXCLUDE_DIRS)), help="Comma-separated list of directory names to exclude.")
    p.add_argument("--max-size", type=int, default=DEFAULT_MAX_SIZE, help=f"Max file size in bytes to include (default {DEFAULT_MAX_SIZE}).")
    p.add_argument("--no-verbose", action="store_true", help="Disable verbose prints.")
    return p.parse_args()

def main():
    args = parse_args()
    root = Path(args.root).resolve()
    out = Path(args.out).resolve()
    include_exts = set([e.strip().lower() for e in args.exts.split(",") if e.strip()])
    exclude_dirs = set([d.strip() for d in args.exclude.split(",") if d.strip()])
    verbose = not args.no_verbose

    if not root.exists():
        print(f"Root path does not exist: {root}", file=sys.stderr)
        sys.exit(2)

    collect_and_write(root, out, include_exts, exclude_dirs, args.max_size, verbose=verbose)

if __name__ == "__main__":
    main()
