"""Verify every relative Dart import resolves to a file that exists.

Catches the "missing file" class of error without needing the Flutter SDK.
Package imports (package:flutter/...) are listed separately so they can be
checked against pubspec dependencies by eye.
"""
import io
import os
import re
import sys

IMPORT_RE = re.compile(r"""^\s*(?:import|export|part)\s+['"]([^'"]+)['"]""", re.M)


def main() -> int:
    missing = []
    packages = set()
    dart_files = []

    for root, _, files in os.walk('lib'):
        for name in files:
            if name.endswith('.dart'):
                dart_files.append(os.path.join(root, name))

    for root, _, files in os.walk('test'):
        for name in files:
            if name.endswith('.dart'):
                dart_files.append(os.path.join(root, name))

    for path in dart_files:
        src = io.open(path, encoding='utf-8').read()
        for target in IMPORT_RE.findall(src):
            if target.startswith('dart:'):
                continue
            if target.startswith('package:'):
                packages.add(target.split('/')[0].replace('package:', ''))
                # A package: import of this app resolves into lib/.
                if target.startswith('package:m_teer_mobile/'):
                    rel = target.replace('package:m_teer_mobile/', 'lib/')
                    if not os.path.exists(rel):
                        missing.append('{} -> {}'.format(path, target))
                continue

            resolved = os.path.normpath(os.path.join(os.path.dirname(path), target))
            if not os.path.exists(resolved):
                missing.append('{} -> {} (expected {})'.format(path, target, resolved))

    print('Dart files scanned: {}'.format(len(dart_files)))
    print('External packages referenced: {}'.format(', '.join(sorted(packages))))
    print('')

    if missing:
        print('MISSING IMPORT TARGETS:')
        for entry in missing:
            print('  ' + entry)
        return 1

    print('All relative and in-app imports resolve.')
    return 0


if __name__ == '__main__':
    sys.exit(main())
