"""Retained build_file_index.py research algorithms. Use analysis.py for portable CLI; see README and provenance."""
import argparse
from collections import Counter, defaultdict
import csv
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import re
import sqlite3
import stat
import tempfile
DEFAULT_ROOT = Path('.')
DEFAULT_MAP = Path('move-map.tsv')
PACKET = Path('.')
EXCLUDED_DIR_NAMES = {'.git', '.venv', 'venv', 'node_modules', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', 'htr_env'}
EXCLUDED_ROOT_FILES = {'INDEX.md', 'README.md'}

def now():
    return datetime.now(timezone.utc).isoformat()

def write_json(path, value):
    path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n')

def resolution(value):
    """Resolve only explicit absolute paths (or ~/); retain raw recorded value."""
    result = {'recorded': value}
    if value is None or value == '':
        return dict(result, state='not_provided')
    if not isinstance(value, str):
        return dict(result, state='invalid_path_value')
    if re.match('^[a-zA-Z][a-zA-Z0-9+.-]*://', value):
        return dict(result, state='URL', checked_network=False)
    path = os.path.expanduser(value) if value.startswith('~/') else value
    if not os.path.isabs(path):
        return dict(result, state='relative_unresolved')
    try:
        if os.path.exists(path):
            return dict(result, state='exactexists', checked_path=path, is_symlink=os.path.islink(path))
        if os.path.lexists(path):
            return dict(result, state='missing', checked_path=path, is_symlink=True, reason='dangling_symlink')
        components = re.split('\\s+\\+\\s+(?=/)|;\\s*(?=/)', path)
        if len(components) > 1 and all((os.path.isabs(component) for component in components)):
            return dict(result, state='composite', components=[resolution(component) for component in components], parsing='explicit separator between absolute paths; original string retained')
        base = re.sub('(?::L?\\d+(?:[-:]\\d+)?|#[^/]+)$', '', path)
        if base != path and os.path.exists(base):
            return dict(result, state='locus-suffix', checked_path=base, suffix=path[len(base):])
        return dict(result, state='missing', checked_path=path)
    except (OSError, ValueError) as exc:
        return dict(result, state='stat_error', error=str(exc))

def image_object_resolution(value):
    """Keep registered object metadata; inspect only explicitly recorded paths."""
    paths = []
    path_keys = {'dir', 'path', 'file', 'files', 'sample', 'images', 'pdf', 'source', 'manifest', 'iiif_manifest', 'fetch_log', 'pdf_on_disk', 'on_disk_pdf_downloads', 'pdf_renamed_from'}

    def visit(item, location='', parent_key=''):
        if isinstance(item, dict):
            for key, child in item.items():
                visit(child, f'{location}.{key}' if location else key, key)
        elif isinstance(item, list):
            for index, child in enumerate(item):
                visit(child, f'{location}[{index}]', parent_key)
        elif isinstance(item, str):
            is_explicit = item.startswith(('/', '~/')) or bool(re.match('^[a-zA-Z][a-zA-Z0-9+.-]*://', item))
            if is_explicit or parent_key in path_keys or parent_key.endswith(('_dir', '_path', '_paths', '_local')):
                paths.append({'field': location, 'resolution': resolution(item)})
    visit(value)
    return {'state': 'object_metadata', 'recorded': value, 'paths': paths}

def scan(root, out, *, exclude_navigation=True, exclude_catalog=True):
    errors, excluded, rows = ([], [], [])
    root = root.absolute()
    out = out.absolute()
    stack = [root]
    while stack:
        directory = stack.pop()
        try:
            with os.scandir(directory) as iterator:
                entries = sorted(iterator, key=lambda entry: entry.name)
        except OSError as exc:
            errors.append({'path': str(directory), 'error': str(exc)})
            continue
        for entry in entries:
            path = Path(entry.path)
            rel = path.relative_to(root).as_posix()
            if path == out or (exclude_catalog and path == root / 'catalog') or (exclude_navigation and directory == root and (entry.name in EXCLUDED_ROOT_FILES)):
                excluded.append({'path': rel, 'reason': 'generated index output'})
                continue
            try:
                row = file_metadata(path, rel)
                kind = row['kind']
                if kind == 'directory' and entry.name in EXCLUDED_DIR_NAMES:
                    row['descendants_excluded'] = 'dependency or cache directory'
                    excluded.append({'path': rel, 'reason': row['descendants_excluded']})
                elif kind == 'directory':
                    stack.append(path)
                rows.append(row)
            except OSError as exc:
                errors.append({'path': str(path), 'error': str(exc)})
    return (sorted(rows, key=lambda row: row['path']), errors, excluded)

def file_metadata(path, rel):
    st = path.lstat()
    kind = 'symlink' if stat.S_ISLNK(st.st_mode) else 'directory' if stat.S_ISDIR(st.st_mode) else 'file' if stat.S_ISREG(st.st_mode) else 'special'
    row = {'path': rel, 'absolute_path': str(path), 'kind': kind, 'size_bytes': st.st_size, 'mtime_ns': st.st_mtime_ns, 'mode': stat.S_IMODE(st.st_mode)}
    if kind == 'symlink':
        row['symlink_target'] = os.readlink(path)
        try:
            row['resolved_target'] = str(path.resolve())
        except (OSError, RuntimeError) as exc:
            row['resolved_target_error'] = str(exc)
        row['target_state'] = resolution(str(path))
    return row

def load_sources(root, registry=None):
    """Validate declared roots before output writes; never infer scope from names."""
    explicit = registry is not None
    registry = Path(registry) if explicit else root / 'tools/file_index_sources.json'
    if not registry.exists():
        if explicit:
            raise ValueError(f'Source registry missing: {registry}')
        return ([], [], {'path': str(registry), 'state': 'not_configured'})
    data = json.loads(registry.read_text())
    if not isinstance(data, dict) or data.get('schema_version') != 1 or (not isinstance(data.get('external_roots'), list)):
        raise ValueError('Source registry requires schema_version 1 and external_roots array.')
    if not isinstance(data.get('external_files', []), list):
        raise ValueError('external_files must be an array.')

    def absolute_path(value, label):
        if not isinstance(value, str) or not value or (not Path(value).is_absolute()) or ('..' in Path(value).parts):
            raise ValueError(f'{label} must be an absolute path without parent traversal.')
        path = Path(value).absolute()
        if path == Path(path.anchor):
            raise ValueError(f'{label} cannot be a filesystem root.')
        try:
            resolved = path.resolve()
        except (OSError, RuntimeError) as exc:
            raise ValueError(f'{label} cannot be resolved safely: {path}') from exc
        if resolved != path or path.is_symlink():
            raise ValueError(f'{label} cannot be a symlink or pass through one: {path}')
        return path
    bases_raw = data.get('allowed_external_bases', [str(root.parent / 'working')])
    if not isinstance(bases_raw, list) or not bases_raw:
        raise ValueError('allowed_external_bases must be a nonempty array of absolute paths.')
    bases = [absolute_path(value, 'Allowed external base') for value in bases_raw]
    sources, errors, ids, paths = ([], [], set(), [])
    declarations = [('root', item) for item in data['external_roots']]
    declarations += [('file', item) for item in data.get('external_files', [])]
    for source_type, item in declarations:
        if not isinstance(item, dict):
            raise ValueError('Every external root must be an object.')
        identifier, label = (item.get('id'), item.get('label'))
        if not isinstance(identifier, str) or not re.fullmatch('[A-Za-z0-9][A-Za-z0-9._-]*', identifier):
            raise ValueError('Every external root needs a stable alphanumeric id (._- allowed).')
        if identifier in ids:
            raise ValueError(f'Duplicate external root id: {identifier}')
        if not isinstance(label, str) or not label.strip():
            raise ValueError(f'External root {identifier} needs a nonempty label.')
        metadata = {}
        for key in ('aliases', 'provenance', 'entrypoints'):
            value = item.get(key, [])
            if not isinstance(value, list) or any((not isinstance(part, str) for part in value)):
                raise ValueError(f'{identifier}.{key} must be an array of strings.')
            metadata[key] = value
        path = absolute_path(item.get('path'), f'External root {identifier}')
        if not any((path.is_relative_to(base) for base in bases)):
            raise ValueError(f'External root outside declared allowed bases: {path}')
        if path.is_relative_to(root) or root.is_relative_to(path):
            raise ValueError(f'External root overlaps canonical scan root: {path}')
        if any((path.is_relative_to(other) or other.is_relative_to(path) for other in paths)):
            raise ValueError(f'Duplicate or overlapping external root: {path}')
        if path.exists() and (not (path.is_dir() if source_type == 'root' else path.is_file())):
            raise ValueError(f'External {source_type} has the wrong filesystem kind: {path}')
        state = ('directory' if source_type == 'root' else 'file') if path.exists() else 'missing'
        source = dict(id=identifier, path=str(path), label=label, state=state, source_type=source_type, **metadata)
        sources.append(source)
        if state == 'missing':
            errors.append({'id': identifier, 'path': str(path), 'error': f'registered external {source_type} missing'})
        ids.add(identifier)
        paths.append(path)
    return (sources, errors, {'path': str(registry.absolute()), 'state': 'loaded', 'allowed_external_bases': [str(path) for path in bases]})

def research_navigation(root):
    path = root / 'tools/research_navigation.md'
    if not path.exists():
        return None
    text = path.read_text().strip()
    if not text.startswith('## Current research and evidence\n'):
        raise ValueError(f'{path} must contain the complete Current research and evidence section.')
    if '\n## Manuscripts, images and working corpora' in text:
        raise ValueError(f'{path} must contain only the maintained research section.')
    return text.splitlines()

def _sqlite_source_exports(db_path):
    connection = sqlite3.connect(db_path.absolute().as_uri() + '?mode=ro', uri=True)
    connection.row_factory = sqlite3.Row
    connection.execute('BEGIN')
    exports = {}
    specs = {'findings': 'id, code, title, status, source_path, working_file', 'manuscripts': 'id, shelfmark, title, status, source_path, image_paths_json', 'citations': 'id, entity_type, entity_id, source_path, page_or_folio'}
    try:
        for table, fields in specs.items():
            records = []
            for raw in connection.execute(f'SELECT {fields} FROM {table} ORDER BY id'):
                record = dict(raw)
                paths = {'source_path': resolution(record.get('source_path'))}
                if table == 'findings':
                    record['finding_id'] = f"F{record['id']}"
                    paths['working_file'] = resolution(record.get('working_file'))
                if table == 'manuscripts':
                    try:
                        images = json.loads(record['image_paths_json'] or '[]')
                        if isinstance(images, list):
                            paths['image_paths'] = [image_object_resolution(image) if isinstance(image, dict) else resolution(image) for image in images]
                        elif isinstance(images, dict):
                            paths['image_paths'] = image_object_resolution(images)
                        else:
                            paths['image_paths'] = {'state': 'invalid_image_paths_shape', 'recorded': images}
                    except (ValueError, TypeError) as exc:
                        paths['image_paths'] = {'state': 'invalid_image_paths_json', 'error': str(exc)}
                record['path_resolution'] = paths
                records.append(record)
            exports[table] = records
    finally:
        connection.rollback()
        connection.close()
    return exports

def map_exports(move_map):
    if move_map is None:
        return [], []
    rows = []
    if not move_map.exists():
        return (rows, [{'path': str(move_map), 'error': 'canonical move map missing'}])
    with move_map.open(newline='') as stream:
        for number, row in enumerate(csv.DictReader(stream, delimiter='\t'), start=2):
            old, new, *other = row.values()
            dest = new if new.startswith('/') else str(move_map.parent / new)
            rows.append({'map_line': number, 'old_path_under_hail': old, 'new_path_recorded': new, 'type': other[0] if other else '', 'basis': other[1] if len(other) > 1 else '', 'resolution': resolution(dest) if not new.startswith('(') else {'recorded': new, 'state': 'non_path_description'}})
    return (rows, [])

def jsonl(path, rows):
    with path.open('w') as stream:
        for row in rows:
            stream.write(json.dumps(row, ensure_ascii=False) + '\n')

def link(label, path):
    return f'[{label}](<{path}>)'

def build(args):
    root, out = (args.root.absolute(), args.output.absolute())
    if out == root or root.is_relative_to(out) or out.is_symlink():
        raise ValueError('Output must be a dedicated non-symlink directory, not the scan root or an ancestor.')
    sources, registration_errors, registry = load_sources(root, getattr(args, 'sources', None))
    if any((Path(source['path']).is_relative_to(out) for source in sources)):
        raise ValueError('Output cannot be a registered scan root or an ancestor of one.')
    navigation = research_navigation(root) if args.write_navigation else None
    out.mkdir(parents=True, exist_ok=True)
    started = now()
    rows, errors, excluded = scan(root, out)
    canonical_counts = Counter((row['kind'] for row in rows))
    canonical_entry_count = len(rows)
    for source in sources:
        if source['state'] == 'missing':
            source['entry_count'] = 0
            source['kind_counts'] = {}
            continue
        if source['source_type'] == 'file':
            packet_errors, packet_excluded = ([], [])
            try:
                packet_rows = [file_metadata(Path(source['path']), Path(source['path']).name)]
            except OSError as exc:
                packet_rows = []
                packet_errors = [{'path': source['path'], 'error': str(exc)}]
        else:
            packet_rows, packet_errors, packet_excluded = scan(Path(source['path']), out, exclude_navigation=False, exclude_catalog=False)
        prefix = 'external/' + source['id'] + '/'
        source['entry_count'] = len(packet_rows)
        source['kind_counts'] = dict(Counter((row['kind'] for row in packet_rows)))
        for row in packet_rows:
            row['relative_path'] = row['path']
            row['path'] = prefix + row['path']
            row['scan_root'] = source['path']
            row['source_type'] = source['source_type']
            row['packet_id'] = source['id']
            row['packet_label'] = source['label']
            for key in ('aliases', 'provenance', 'entrypoints'):
                row[key] = source[key]
        rows.extend(packet_rows)
        errors.extend((dict(error, packet_id=source['id']) for error in packet_errors))
        excluded.extend((dict(item, path=prefix + item['path'], packet_id=source['id']) for item in packet_excluded))
    rows.sort(key=lambda row: row['path'])
    if len({row['path'] for row in rows}) != len(rows):
        raise ValueError('External namespace collides with canonical metadata identities.')
    exports = source_exports(args.substrate)
    routes, route_errors = map_exports(args.move_map)
    counts = Counter((row['kind'] for row in rows))
    cards = defaultdict(lambda: Counter())
    card_paths = {}
    for row in rows:
        if 'packet_id' in row:
            key = 'external/' + row['packet_id']
            card_paths[key] = row['scan_root']
        else:
            key = row['path'].split('/')[0] if '/' in row['path'] else '(root files)'
            card_paths[key] = str(root if key == '(root files)' else root / key)
        cards[key][row['kind']] += 1
        if row['kind'] == 'file':
            cards[key]['bytes'] += row['size_bytes']
    summary = {'format_version': 1, 'collected_at_utc': started, 'finished_at_utc': now(), 'root': str(root), 'substrate_read_only': str(args.substrate), 'entry_count': len(rows), 'file_count': counts['file'], 'symlink_count': counts['symlink'], 'kind_counts': dict(counts), 'canonical_root_counts': {'entry_count': canonical_entry_count, 'kind_counts': dict(canonical_counts)}, 'external_root_counts': {'entry_count': len(rows) - canonical_entry_count, 'kind_counts': dict(counts - canonical_counts)}, 'source_registry': registry, 'registered_external_roots': [source for source in sources if source['source_type'] == 'root'], 'registered_external_files': [source for source in sources if source['source_type'] == 'file'], 'registration_error_count': len(registration_errors), 'registration_errors': registration_errors, 'substrate_counts': {table: len(records) for table, records in exports.items()}, 'finding_status_counts': dict(Counter((row['status'] for row in exports['findings']))), 'move_route_count': len(routes), 'scan_error_count': len(errors), 'scan_errors': errors, 'route_errors': route_errors, 'excluded_directory_names': sorted(EXCLUDED_DIR_NAMES), 'excluded_paths': excluded, 'scope': 'Local lstat metadata from canonical root and explicitly registered external roots/files only; directory symlinks never traversed; no image hashing or discovery of additional roots.', 'self_exclusion': 'Whole selected output directory, canonical root catalog directory and canonical INDEX.md/README.md excluded. External packet INDEX.md/README.md are source files and included.', 'staleness': 'A snapshot, not a live watcher. Rebuild after changes. Collection interval and file mtimes are recorded; substrate tables come from one read transaction.', 'path_resolution': 'Only exact absolute or ~/ paths are checked; URLs not fetched; no guessed replacements. Explicit separators between absolute paths become composite records after checking literal existence. Locus suffix recognized only with existing base. Relative paths unresolved.'}
    jsonl(out / 'files.jsonl', rows)
    for table, records in exports.items():
        jsonl(out / f'{table}.jsonl', records)
    jsonl(out / 'move_routes.jsonl', routes)
    write_json(out / 'SUMMARY.json', summary)
    write_json(out / 'registered_sources.json', {'registry': registry, 'sources': sources, 'registration_errors': registration_errors})
    write_json(out / 'DIRECTORIES.json', dict(sorted(cards.items())))
    text = ['# Directory cards', '', f'Collected {started}. Counts include descendants except declared cache/dependency exclusions; symlink targets are not traversed.', '', '| Directory | Files | Directories | Symlinks | Regular file bytes |', '|---|---:|---:|---:|---:|']
    for key, card in sorted(cards.items()):
        display = link(key.replace('|', '&#124;'), card_paths[key])
        text.append(f"| {display} | {card['file']} | {card['directory']} | {card['symlink']} | {card['bytes']} |")
    (out / 'DIRECTORIES.md').write_text('\n'.join(text) + '\n')
    fd, temp_name = tempfile.mkstemp(prefix='catalog-', suffix='.sqlite', dir=out)
    os.close(fd)
    try:
        con = sqlite3.connect(temp_name)
        con.executescript('CREATE TABLE records (kind TEXT NOT NULL, id TEXT NOT NULL, search_text TEXT NOT NULL, record_json TEXT NOT NULL); CREATE INDEX records_kind ON records(kind); CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);')
        batches = [('file', rows)] + [(name[:-1], records) for name, records in exports.items()] + [('route', routes)]
        for kind, records in batches:
            con.executemany('INSERT INTO records VALUES (?, ?, ?, ?)', ((kind, str(row.get('id', row.get('path', row.get('map_line', '')))), json.dumps(row, ensure_ascii=False).lower(), json.dumps(row, ensure_ascii=False)) for row in records))
        con.execute('INSERT INTO metadata VALUES (?, ?)', ('summary', json.dumps(summary)))
        con.commit()
        con.close()
        os.replace(temp_name, out / 'catalog.sqlite')
    finally:
        if os.path.exists(temp_name):
            os.unlink(temp_name)
    if args.write_navigation:
        raise ValueError('Navigation writes are unavailable in the portable edition.')
    print(json.dumps({key: summary[key] for key in ('collected_at_utc', 'entry_count', 'file_count', 'symlink_count', 'substrate_counts', 'move_route_count', 'scan_error_count', 'registration_error_count')}))
    return summary

def find(args):
    con = sqlite3.connect((args.output.absolute() / 'catalog.sqlite').as_uri() + '?mode=ro', uri=True)
    try:
        summary = json.loads(con.execute("SELECT value FROM metadata WHERE key='summary'").fetchone()[0])
        print(json.dumps({'snapshot_utc': summary['collected_at_utc'], 'term': args.term, 'kind': args.kind, 'limit': args.limit}))
        finding_match = re.fullmatch('F-?(\\d+)', args.term, flags=re.IGNORECASE)
        if finding_match and args.kind in ('all', 'finding'):
            sql = "SELECT kind, id, record_json FROM records WHERE ((kind='finding' AND id=?) OR (kind!='finding' AND instr(search_text, ?) > 0))"
            params = [str(int(finding_match.group(1))), args.term.lower()]
        else:
            sql = 'SELECT kind, id, record_json FROM records WHERE instr(search_text, ?) > 0'
            params = [args.term.lower()]
        if args.kind != 'all':
            sql += ' AND kind = ?'
            params.append(args.kind)
        sql += " ORDER BY CASE kind WHEN 'finding' THEN 0 WHEN 'manuscript' THEN 1 WHEN 'route' THEN 2 WHEN 'file' THEN 3 ELSE 4 END,\n            CASE WHEN kind = 'file' AND (\n                instr(lower(id), ?) > 0 OR\n                instr(lower(coalesce(json_extract(record_json, '$.absolute_path'), '')), ?) > 0\n            ) THEN 0 ELSE 1 END, id LIMIT ?"
        params.extend([args.term.lower(), args.term.lower(), args.limit])
        for kind, identifier, payload in con.execute(sql, params):
            print(json.dumps({'kind': kind, 'id': identifier, 'record': json.loads(payload)}, ensure_ascii=False))
    finally:
        con.close()

def source_exports(db_path):
    if db_path is None:
        return {name: [] for name in ('findings', 'manuscripts', 'citations')}
    if Path(db_path).suffix.lower() == '.json':
        data = json.loads(Path(db_path).read_text())
        tables = data.get('tables', data)
        result = {name: [dict(row) for row in tables.get(name, [])] for name in ('findings', 'manuscripts', 'citations')}
        for row in result['findings']:
            row['finding_id'] = 'F' + str(row['id'])
        return result
    return _sqlite_source_exports(db_path)
