"""Console entry point: build or refresh a repository graph.

    graph-builder --root <project> [--out <path>/info_graph.json] [--force]

The graph always lands at ``<root>/.zyte/info_graph.json``; ``--out`` copies it
elsewhere when a caller wants the artifact at a different path.
"""

from __future__ import annotations

import argparse
import shutil
import sys
from pathlib import Path

from . import scan
from . import store as _store


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="graph-builder", description="Build the Zyte repository graph.")
    parser.add_argument("--root", default=".", help="Project directory to index")
    parser.add_argument("--out", default=None, help="Also copy the graph JSON to this path")
    parser.add_argument("--force", action="store_true", help="Rebuild even when the graph is fresh")
    args = parser.parse_args(sys.argv[1:] if argv is None else argv)

    root = Path(args.root).resolve()
    if not root.is_dir():
        print(f"graph-builder: not a directory: {root}", file=sys.stderr)
        return 1

    result = scan(root, force=args.force)
    canonical = _store.info_graph_path(root)
    if not canonical.is_file():
        print(f"graph-builder: scan produced no graph at {canonical}", file=sys.stderr)
        return 1

    if args.out:
        out = Path(args.out)
        try:
            if out.resolve() != canonical.resolve():
                out.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(canonical, out)
        except OSError as error:
            print(f"graph-builder: could not copy graph to {out}: {error}", file=sys.stderr)
            return 1

    verb = "up to date" if result.get("skipped") else "indexed"
    print(
        f"graph-builder: {verb} - {result.get('files', 0)} files, "
        f"{result.get('symbols', 0)} symbols, {result.get('edges', 0)} edges "
        f"in {result.get('elapsed_ms', 0)} ms"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
