"""The venvy pip hook code — injected into venv site-packages."""

HOOK_PY = r'''"""
venvy pip hook - auto-tracks pip install/uninstall in requirements.txt.
Managed by venvy. Do not edit manually.
"""
import sys
import os
import re


def _find_req_file():
    import json
    from pathlib import Path
    cwd = Path.cwd()
    for d in [cwd] + list(cwd.parents):
        cfg = d / '.venvy' / 'config.json'
        if cfg.exists():
            try:
                data = json.loads(cfg.read_text(encoding='utf-8'))
                return d / data.get('requirements_file', 'requirements.txt')
            except Exception:
                pass
            break
        if d == d.parent:
            break
    return cwd / 'requirements.txt'


def _parse(f):
    out = {}
    if not f.exists():
        return out
    for line in f.read_text(encoding='utf-8').splitlines():
        s = line.strip()
        if not s or s.startswith('#'):
            continue
        m = re.match(r'^([A-Za-z0-9_\-\.]+)', s)
        if m:
            out[m.group(1).lower().replace('-', '_')] = s
    return out


def _write(f, pkgs):
    f.parent.mkdir(parents=True, exist_ok=True)
    f.write_text('\n'.join(sorted(pkgs.values(), key=str.lower)) + '\n', encoding='utf-8')


def _get_version(pkg_name):
    try:
        import importlib.metadata
        return importlib.metadata.version(pkg_name)
    except Exception:
        return None


def _track_install(args):
    req = _find_req_file()
    existed = req.exists()
    existing = _parse(req)
    changed = False
    for pkg in args:
        if pkg.startswith('-') or pkg.startswith('http') or '/' in pkg or pkg.startswith('.'):
            continue
        pkg_clean = re.split(r'[\[><=!;@\s]', pkg)[0].strip()
        if not pkg_clean:
            continue
        v = _get_version(pkg_clean)
        if v:
            key = pkg_clean.lower().replace('-', '_')
            entry = f'{pkg_clean}=={v}'
            if existing.get(key) != entry:
                existing[key] = entry
                changed = True
                sys.stdout.write(f'\n[venvy] + {entry} -> {req.name}\n')
    if changed:
        if not existed:
            sys.stdout.write(f'[venvy] Created {req.name}\n')
        _write(req, existing)


def _track_uninstall(args):
    req = _find_req_file()
    if not req.exists():
        return
    existing = _parse(req)
    changed = False
    for pkg in args:
        if pkg.startswith('-'):
            continue
        pkg_clean = re.split(r'[\[><=!;@\s]', pkg)[0].strip()
        if not pkg_clean:
            continue
        key = pkg_clean.lower().replace('-', '_')
        if key in existing:
            existing.pop(key)
            changed = True
            sys.stdout.write(f'\n[venvy] - {pkg_clean} -> {req.name}\n')
    if changed:
        _write(req, existing)


def _install_hooks():
    try:
        from pip._internal.commands.install import InstallCommand
        from pip._internal.commands.uninstall import UninstallCommand

        _orig_install = InstallCommand.run
        _orig_uninstall = UninstallCommand.run

        def _hooked_install(self, options, args):
            status = _orig_install(self, options, args)
            try:
                if status == 0 and args:
                    _track_install(args)
            except Exception:
                pass
            return status

        def _hooked_uninstall(self, options, args):
            status = _orig_uninstall(self, options, args)
            try:
                if status == 0 and args:
                    _track_uninstall(args)
            except Exception:
                pass
            return status

        InstallCommand.run = _hooked_install
        UninstallCommand.run = _hooked_uninstall
    except Exception:
        pass


_install_hooks()
'''

HOOK_PTH = 'import venvy_hook\n'


def get_hook_files():
    return HOOK_PY, HOOK_PTH
