import os
import re
from collections import defaultdict, deque

ROOT = "lib"

IMPORT_RE = re.compile(r"import\s+'package:[^/]+/(.+?)';")

def list_dart_files():
    files = []
    for root, _, filenames in os.walk(ROOT):
        for f in filenames:
            if f.endswith(".dart"):
                files.append(os.path.join(root, f))
    return files

def normalize(path):
    return path.replace("\\", "/")

def build_graph(files):
    graph = defaultdict(list)
    reverse_graph = defaultdict(list)

    for f in files:
        rel = normalize(f)
        with open(f, "r", encoding="utf-8") as fh:
            content = fh.read()

        for m in IMPORT_RE.findall(content):
            imported = normalize(os.path.join(ROOT, m))
            if imported in files:
                graph[rel].append(imported)
                reverse_graph[imported].append(rel)

    return graph, reverse_graph

def reachable_from_main(graph):
    start = "lib/main.dart"
    visited = set()
    queue = deque([start])

    while queue:
        node = queue.popleft()
        if node in visited:
            continue
        visited.add(node)
        for nxt in graph.get(node, []):
            queue.append(nxt)

    return visited

files = list_dart_files()
files = [normalize(f) for f in files]

graph, reverse_graph = build_graph(files)
reachable = reachable_from_main(graph)

unused = sorted(set(files) - reachable)

print("\n=== FILE NON USATI ===")
for f in unused:
    print(f)

print("\n=== DIPENDENZE ===")
for f in sorted(files):
    print(f"\n{f}")
    print("  importa:")
    for dep in graph[f]:
        print("    -", dep)
    print("  importato da:")
    for dep in reverse_graph[f]:
        print("    -", dep)
