from __future__ import annotations

import argparse
import os
from pathlib import Path

from .loader import load_model
from .mapper import map_to_graph
from .neo4j_writer import Neo4jWriter


def _load_project_dotenv() -> None:
    """Load `.env` from the AIF repo root if python-dotenv is available."""
    try:
        from dotenv import load_dotenv
    except ImportError:
        return
    repo_root = Path(__file__).resolve().parents[2]
    load_dotenv(repo_root / ".env")


def build_arg_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="archimate-to-graph",
        description=(
            "Import an ArchiMate model (Model Exchange Format) into a Neo4j graph.\n\n"
            "This tool is self-contained under `ontology/archimate_to_graph` and "
            "does not depend on or modify the rest of the AIF project."
        ),
    )
    parser.add_argument(
        "--input",
        required=True,
        help="Path to an ArchiMate model file (.archimate / .xml).",
    )
    parser.add_argument(
        "--uri",
        default=None,
        help="Neo4j Bolt URI. Default: NEO4J_BOLT_URI env, else bolt://127.0.0.1:7687.",
    )
    parser.add_argument(
        "--user",
        default=None,
        help="Neo4j username. Default: NEO4J_USER env, else neo4j.",
    )
    parser.add_argument(
        "--password",
        default=None,
        help="Neo4j password. Default: NEO4J_PASSWORD env, else empty string.",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    _load_project_dotenv()
    parser = build_arg_parser()
    parser.set_defaults(
        uri=os.getenv("NEO4J_BOLT_URI", "bolt://127.0.0.1:7687"),
        user=os.getenv("NEO4J_USER", "neo4j"),
        password=os.getenv("NEO4J_PASSWORD", ""),
    )
    args = parser.parse_args(argv)

    model_path = Path(args.input)
    if not model_path.exists():
        parser.error(f"Input file does not exist: {model_path}")

    model = load_model(model_path)
    nodes, edges = map_to_graph(model)

    writer = Neo4jWriter(args.uri, args.user, args.password)
    try:
        writer.import_graph(nodes, edges)
    finally:
        writer.close()

    return 0


if __name__ == "__main__":  # pragma: no cover
    raise SystemExit(main())

