"""DevAgentDesk local prototype: factual diff inventory, no model requests."""
import argparse
import re
import subprocess
from pathlib import Path


def inventory(diff):
    files = []
    current = None
    old_line = new_line = None
    in_hunk = False
    for line in diff.splitlines():
        if line.startswith('diff --git '):
            in_hunk = False
            current = None
        if not in_hunk and line.startswith('--- '):
            current = {'old': line[4:].split('\t')[0], 'new': '', 'added': 0,
                       'removed': 0, 'hunks': 0, 'evidence': []}
            files.append(current)
        elif not in_hunk and line.startswith('+++ ') and current is not None:
            current['new'] = line[4:].split('\t')[0]
        elif line.startswith('@@ ') and current is not None:
            match = re.match(r'@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@', line)
            if match:
                old_line, new_line = map(int, match.groups())
                current['hunks'] += 1
                in_hunk = True
        elif in_hunk and current is not None:
            if line.startswith('+'):
                current['added'] += 1
                current['evidence'].append(('new', new_line, line[1:]))
                new_line += 1
            elif line.startswith('-'):
                current['removed'] += 1
                current['evidence'].append(('old', old_line, line[1:]))
                old_line += 1
            elif line.startswith(' '):
                new_line += 1
                old_line += 1
    return files


def report(files):
    lines = ['# DevAgentDesk — change inventory', '',
             'Local prototype output. Rule-based inventory; Claude analysis is not connected.',
             'This report does not establish that the changes are correct or tested.', '',
             f'Changed text files: {len(files)}', '',
             '| File | Added | Removed | Hunks |', '| --- | ---: | ---: | ---: |']
    for entry in files:
        name = entry['new'] if entry['new'] != '/dev/null' else entry['old']
        lines.append(f"| {name.replace('|', '&#124;')} | {entry['added']} | {entry['removed']} | {entry['hunks']} |")
    for entry in files:
        lines += ['', f"## {entry['new'] or entry['old']}", '',
                  'Evidence references use old/new file line numbers.', '']
        for side, number, text in entry['evidence'][:60]:
            escaped = text.replace('`', '\\`').replace('\n', ' ')
            lines.append(f'- {side}:{number} — `{escaped}`')
        if len(entry['evidence']) > 60:
            lines.append(f"- {len(entry['evidence']) - 60} more changed lines omitted from this preview.")
    lines += ['', '## Human review checklist', '',
              '- Confirm that the observed changes match the intended behavior.',
              '- Run the relevant existing checks and record their results.',
              '- Check the affected user flow in the actual application.',
              '- Review permissions and external effects if those changed.', '',
              'Binary files, rename-only metadata, and combined merge diffs are outside this prototype inventory.',
              'No code is executed, modified, committed, or sent to a model by this tool.', '']
    return '\n'.join(lines)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument('--diff', type=Path, help='UTF-8 unified diff file')
    source.add_argument('--repo', type=Path, help='Read working-tree changes from a Git repository')
    parser.add_argument('--cached', action='store_true', help='Use staged changes with --repo')
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    if args.cached and not args.repo:
        parser.error('--cached requires --repo')
    if args.diff:
        diff = args.diff.read_text(encoding='utf-8-sig')
    else:
        command = ['git', '-C', str(args.repo.resolve()), 'diff', '--no-ext-diff',
                   '--no-textconv', '--no-color', '--no-prefix', '--unified=3']
        if args.cached:
            command.append('--cached')
        result = subprocess.run(command, capture_output=True, encoding='utf-8', errors='replace')
        if result.returncode:
            parser.exit(1, 'Git read failed; verify the repository path.\n')
        diff = result.stdout
    args.output.write_text(report(inventory(diff)), encoding='utf-8')
    print(f'Wrote local inventory to {args.output.resolve()}')


if __name__ == '__main__':
    main()
