#!/usr/bin/env python3
"""Orchestrate the pinned filler. Never edit Word or manufacture a user reply."""
import argparse
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys

ROOT = Path(__file__).resolve().parent.parent
MAX_JSON = 512 * 1024
MAX_FILE = 8 * 1024 * 1024
SCHEMA = 'schemas/input.schema.json'
WORK_DIRECTORY = None


class Failure(Exception):
    def __init__(self, code, field, message, next_step):
        self.issue = dict(code=code, field=field, message=message, next_step=next_step)


def fail(code, field, message, next_step):
    raise Failure(code, field, message, next_step)


def sha(body):
    return hashlib.sha256(body).hexdigest()


def read_file(path, limit=MAX_JSON):
    fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0))
    with os.fdopen(fd, 'rb') as handle:
        info = os.fstat(handle.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
            raise ValueError('An ordinary file within the size limit is required: ' + str(path))
        body = handle.read(limit + 1)
        if len(body) > limit:
            raise ValueError('File size limit exceeded: ' + str(path))
        return body


def unique(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('Duplicate JSON key: ' + key)
        result[key] = value
    return result


def parse(body):
    return json.loads(body, object_pairs_hook=unique,
                      parse_constant=lambda value: (_ for _ in ()).throw(ValueError('Invalid number: ' + value)))


def encoded(value):
    return (json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n').encode('utf-8')


def absolute(path):
    # Preserve the final component: read_file/the filler must reject a symlink.
    return Path(os.path.abspath(path.expanduser()))


def write_new(path, body):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, 'wb') as handle:
        handle.write(body)


def inside(base, target):
    """Compare filesystem identities, including case aliases on macOS/Windows."""
    current = target
    while True:
        if current.exists() and os.path.samefile(base, current):
            return True
        parent = current.parent
        if parent == current:
            return False
        current = parent


def private_workdir(path):
    if not path.is_absolute() or os.path.lexists(path):
        fail('NEW_PRIVATE_DIRECTORY', '--work-dir', 'Use a new absolute directory; nothing is overwritten.',
             'Choose a new private directory in the agreed user workspace. Its parent must exist.')
    parent = path.parent.resolve(strict=True)
    target = parent / path.name
    root = ROOT.resolve(strict=True)
    publication = root.parent.parent if root.parent.name in ('contracts', 'ai_legal') and root.parent.parent.name == 'public' else None
    if inside(root, target) or (publication and inside(publication, target)):
        fail('PRIVATE_DIRECTORY', '--work-dir', 'Customer data and replies must stay outside the bundle and site public directory.',
             'Choose a private user directory. Do not use a symlink or case alias of a public directory.')
    target.mkdir(mode=0o700)
    return target.resolve(strict=True)


def verified_bundle(template):
    """Trust starts with the downloader obtained through an established channel."""
    downloader = read_file(ROOT / 'scripts/download.py').decode('utf-8')
    def pin(name):
        found = re.search(r'^' + name + r" = '([0-9a-f]{64})'$", downloader, re.M)
        if not found:
            raise ValueError('Missing bootstrap pin: ' + name)
        return found[1]
    release_body = read_file(ROOT / 'release.json')
    if sha(release_body) != pin('RELEASE_SHA256'):
        raise ValueError('Release differs from the trusted downloader')
    release = parse(release_body)
    required = {'agent/scripts/wizard.py', 'agent/' + SCHEMA, 'agent/fields.json',
                f'agent/templates/{template}.docx', f'agent/data/{template}.json'}
    seen = set()
    for row in release['files']:
        relative = row['path']
        if (not relative.startswith('agent/') or '\\' in relative or
                any(piece in ('', '.', '..') for piece in relative.split('/'))):
            raise ValueError('Invalid release path')
        if row['template'] not in (None, template):
            continue
        body = read_file(ROOT / relative.removeprefix('agent/'), MAX_FILE)
        if len(body) != row['size'] or sha(body) != row['sha256']:
            raise ValueError('Resource differs from the release: ' + relative)
        seen.add(relative)
    if not required <= seen:
        raise ValueError('Required wizard resources are missing')
    filler = ROOT / 'scripts/fill_contract.py'
    if sha(read_file(filler)) != pin('FILLER_SHA256'):
        raise ValueError('Filler differs from the trusted downloader')
    return filler, release


def schema_issues(value, schema, root=None, pointer=''):
    """Evaluate the bounded keyword subset used by our pinned 2020-12 schema."""
    root = schema if root is None else root
    issues = []
    def error(keyword, expected):
        issue = dict(code='INPUT_FORMAT', field=pointer or '/', keyword=keyword, expected=expected,
                     next_step='Copy the exact value from its source. Ask the user about missing or ambiguous values; do not convert or guess silently.')
        for key in ('description', 'examples'):
            if key in schema:
                issue[key] = schema[key]
        issues.append(issue)
    if '$ref' in schema:
        reference = schema['$ref']
        if not reference.startswith('#/$defs/'):
            raise ValueError('Only local schema definitions are supported')
        issues += schema_issues(value, root['$defs'][reference.removeprefix('#/$defs/')], root, pointer)
    for sub in schema.get('allOf', []):
        issues += schema_issues(value, sub, root, pointer)
    if 'if' in schema:
        branch = 'else' if schema_issues(value, schema['if'], root, pointer) else 'then'
        issues += schema_issues(value, schema.get(branch, {}), root, pointer)
    kinds = dict(object=isinstance(value, dict), array=isinstance(value, list), string=isinstance(value, str),
                 integer=type(value) is int, null=value is None)
    types = schema.get('type')
    if types is not None and not any(kinds.get(kind, False) for kind in ([types] if isinstance(types, str) else types)):
        error('type', types)
        return issues
    if 'const' in schema and (type(value) is not type(schema['const']) or value != schema['const']):
        error('const', schema['const'])
    if 'enum' in schema and not any(type(value) is type(item) and value == item for item in schema['enum']):
        error('enum', schema['enum'])
    if isinstance(value, dict):
        for key in schema.get('required', []):
            if key not in value:
                issues.append(dict(code='MISSING_FIELD', field=pointer + '/' + key, keyword='required',
                                   next_step='Read the source or ask the user. Do not insert an example value.'))
        properties = schema.get('properties', {})
        for key, item in value.items():
            sub = properties.get(key, schema.get('additionalProperties', {}))
            field = pointer + '/' + key.replace('~', '~0').replace('/', '~1')
            if sub is False:
                issues.append(dict(code='UNKNOWN_FIELD', field=field, keyword='additionalProperties',
                                   next_step='Keep additional information separately and ask how it should be used. Do not discard it silently.'))
            elif isinstance(sub, dict):
                issues += schema_issues(item, sub, root, field)
        if len(value) < schema.get('minProperties', 0):
            error('minProperties', schema['minProperties'])
    if isinstance(value, list):
        for keyword, invalid in [('minItems', len(value) < schema.get('minItems', 0)),
                                 ('maxItems', len(value) > schema.get('maxItems', len(value)))]:
            if invalid:
                error(keyword, schema[keyword])
        for i, item in enumerate(value):
            issues += schema_issues(item, schema.get('items', {}), root, pointer + '/' + str(i))
    if isinstance(value, str):
        for keyword, invalid in [('minLength', len(value) < schema.get('minLength', 0)),
                                 ('maxLength', len(value) > schema.get('maxLength', len(value))),
                                 ('pattern', 'pattern' in schema and re.fullmatch(schema['pattern'], value) is None)]:
            if invalid:
                error(keyword, schema[keyword])
    if type(value) is int:
        for keyword, invalid in [('minimum', value < schema.get('minimum', value)),
                                 ('maximum', value > schema.get('maximum', value))]:
            if invalid:
                error(keyword, schema[keyword])
    return issues


def execute(filler, args, work, step, comparison=False):
    directory = work / step
    directory.mkdir(mode=0o700)
    command = [sys.executable, '-I', str(filler), *map(str, args)]
    started = dt.datetime.now(dt.timezone.utc).isoformat()
    stdout = directory / 'stdout.txt'
    stderr = directory / 'stderr.txt'
    with stdout.open('xb') as out, stderr.open('xb') as err:
        os.chmod(stdout, 0o600)
        os.chmod(stderr, 0o600)
        try:
            child = subprocess.run(command, cwd=ROOT, stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=180)
            observed = dict(python_started=True, exit_code=child.returncode if child.returncode >= 0 else None,
                            signal=-child.returncode if child.returncode < 0 else None)
        except (OSError, subprocess.TimeoutExpired) as exc:
            observed = dict(python_started=isinstance(exc, subprocess.TimeoutExpired), exit_code=None, launch_error=str(exc))
    metadata = dict(command=command, started_at=started, **observed,
                    stdout_file=str(stdout), stderr_file=str(stderr))
    write_new(directory / 'result.json', encoded(metadata))
    result = None
    try:
        result = parse(read_file(stdout, 2 * MAX_JSON))
    except (OSError, ValueError):
        pass
    if (comparison and observed['exit_code'] == 1 and isinstance(result, dict) and
            result.get('ok') is True and result.get('mode') == 'snapshot_comparison' and result.get('unchanged') is False):
        return result
    if observed['exit_code'] != 0:
        error = Failure('FILLER_FAILED', step, 'The operation failed. Read the original stdout, stderr and result.json.',
                        'Preserve this run and check actual files before retrying in a new directory: ' + str(directory))
        error.issue.update(run_directory=str(directory), **observed)
        if isinstance(result, dict):
            error.issue.update(filler_errors=result.get('errors', []), filler_result=result)
        raise error
    if not isinstance(result, dict) or result.get('ok') is not True:
        raise ValueError('The filler did not report success: ' + step)
    return result


def finish_report(work, release, stage, **details):
    result = dict(ok=True, stage=stage, status='draft', ready_for_delivery=False,
                  release=release['version'], work_directory=str(work),
                  user_identity_verified=False, source_authenticity_verified=False,
                  source_conditions_verified_by_script=False, **details)
    write_new(work / 'report.json', encoded(result))
    return result


def main():
    global WORK_DIRECTORY
    exit_code = 0
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('step', choices=('prepare', 'complete', 'review', 'compare'))
    ap.add_argument('data', type=Path)
    ap.add_argument('--work-dir', type=Path, required=True, help='New absolute private directory; parent must exist')
    ap.add_argument('--sources', type=Path, help='Original document name → original file path; prepare only')
    ap.add_argument('--reply', type=Path, help='Actual complete user reply in UTF-8 without BOM or added final newline; origin/identity must be established by the caller; complete/review only')
    ap.add_argument('--document', type=Path, help='Existing Word; review/compare only')
    ap.add_argument('--snapshot', type=Path, help='Earlier snapshot; compare only')
    ap.add_argument('--snapshot-sha256', help='Earlier trusted external snapshot hash; compare only')
    ap.add_argument('--language', choices=('ru', 'en'), default='ru')
    args = ap.parse_args()
    provided = {key for key in ('sources', 'reply', 'document', 'snapshot', 'snapshot_sha256') if getattr(args, key) is not None}
    allowed = dict(prepare={'sources'}, complete={'reply'}, review={'reply', 'document'},
                   compare={'snapshot', 'snapshot_sha256', 'document'})[args.step]
    required = allowed - {'document'} if args.step == 'compare' else allowed
    if not required <= provided or provided - allowed:
        fail('ARGUMENTS', '/', 'Arguments do not match the selected step.', 'Read scripts/wizard.py --help and guide/10-wizard.md.')
    data = parse(read_file(args.data))
    if not isinstance(data, dict) or data.get('template') not in ('company', 'corporation'):
        fail('TEMPLATE', '/template', 'Choose company or corporation.', 'Ask the user to choose the contract. Do not infer it.')
    filler, release = verified_bundle(data['template'])
    issues = schema_issues(data, parse(read_file(ROOT / SCHEMA)))
    if issues:
        print(json.dumps(dict(ok=False, stage='collect_data', status='draft', ready_for_delivery=False,
                              schema=SCHEMA, errors=issues, work_directory=None), ensure_ascii=False, indent=2))
        return 1
    work = private_workdir(args.work_dir)
    WORK_DIRECTORY = work
    if args.step == 'prepare':
        bound = work / 'bound.json'
        execute(filler, [absolute(args.data), '--bind-sources', absolute(args.sources), '--bound-data', bound], work, '01-bind')
        preview = execute(filler, [bound, '--check', '--language', args.language], work, '02-check')
        proposal = work / 'proposed-confirmation.txt'
        write_new(proposal, preview['approval_text'].encode('utf-8'))
        result = finish_report(work, release, 'await_user_reply', data=str(bound),
                               proposed_confirmation=str(proposal), approval_text=preview['approval_text'],
                               contract_description=preview['contract_description'], source_checks=preview['source_checks'],
                               next_step='Show the entire approval_text and calculations. Obtain one exact actual user reply and save it outside this proposal file. Then run complete with bound.json, --reply and a new private --work-dir.')
    elif args.step == 'compare':
        options = [absolute(args.data), '--compare-snapshot', absolute(args.snapshot), '--snapshot-sha256', args.snapshot_sha256]
        if args.document:
            options += ['--compare-document', absolute(args.document)]
        check = execute(filler, options, work, '01-compare', comparison=True)
        changed = check['unchanged'] is False
        result = finish_report(work, release, 'snapshot_changes_detected' if changed else 'snapshot_compared', check=check,
                               comparison_status='changed_or_incomplete' if changed else 'unchanged',
                               next_step='Differences or unavailable files were detected. Preserve both versions and inspect check.data_changes, data_file_changed, release_changed, document and sources. Follow the applicable branch of guide/07-delivery.md; repeat binding and full confirmation when values, sources or requested edits changed. Repeating the same comparison does not resolve differences.' if changed else
                               'This comparison does not replace the visual and independent review or establish the earlier hash provenance. Follow guide/07-delivery.md.')
        exit_code = 1 if changed else 0
    else:
        preview = execute(filler, [absolute(args.data), '--check', '--language', args.language], work, '01-recheck')
        proposal = absolute(args.data).parent / 'proposed-confirmation.txt'
        if (args.reply.name.casefold() == 'proposed-confirmation.txt' or
                (proposal.exists() and args.reply.exists() and os.path.samefile(proposal, args.reply))):
            fail('PROPOSED_REPLY', '--reply', 'The wizard proposal is not an actual user reply.',
                 'Obtain one complete real user message and save it separately. Establish its origin; do not manufacture or copy a reply.')
        reply = read_file(args.reply).decode('utf-8')
        if reply.replace('\r\n', '\n') != preview['approval_text'].replace('\r\n', '\n'):
            normalized = reply.replace('\r\n', '\n')
            candidate = normalized.removeprefix('\ufeff')
            expected = preview['approval_text'].replace('\r\n', '\n')
            if candidate.startswith(expected) and all(char in ' \t\r\n' for char in candidate[len(expected):]):
                fail('REPLY_FILE_FORMAT', '--reply', 'Only a UTF-8 BOM or trailing whitespace differs from the current complete block. The reply is not accepted or changed.',
                     'Preserve this file and compare it with the actual user message. If the editor added the BOM or final whitespace, save the same actual message as a new UTF-8 file without those additions. Do not copy the proposal. If the actual message itself differs, obtain a new exact full reply.')
            fail('USER_REPLY', '--reply', 'The saved reply differs from the entire current confirmation block.',
                 'Read the actual user message. Show the full current block and obtain a new exact reply; never copy the proposed block as a reply.')
        returned = re.search(r'\nКод подтверждения SHA-256: ([0-9a-f]{64})$', reply.replace('\r\n', '\n'))
        if not returned or returned[1] != preview['approval_sha256']:
            raise ValueError('The code in the actual reply differs from the current data')
        # Populate approval only after the separately supplied reply matches.
        data['approval'] = dict(quote=reply, values=preview['approval_values'])
        approved = work / 'approved.json'
        write_new(approved, encoded(data))
        digest = returned[1]  # From the external reply, never from editable JSON.
        if args.step == 'complete':
            document = work / ('Базовый_черновик.docx' if data['changes'] else 'Договор_черновик.docx')
            options = [approved, '--out', document, '--approved-sha256', digest]
            if data['changes']:
                options += ['--base-for-changes']
            filled = execute(filler, options, work, '02-fill')
            if data['changes']:
                result = finish_report(work, release, 'text_changes_pending', data=str(approved), file=str(document), fill=filled,
                                       next_step='Apply the agreed edits in a separate Word copy using visible marks. Keep the change list. Run review with that copy and the actual reply; follow guide/05-changes.md. The base does not contain these edits.')
            else:
                check = execute(filler, [approved, '--verify', document, '--approved-sha256', digest,
                                        '--snapshot', work / 'snapshot.json'], work, '03-verify')
                result = finish_report(work, release, 'technical_checks_passed', data=str(approved), file=str(document), fill=filled,
                                       check=check, next_step='Save check.saved_snapshot.sha256 separately through an established trusted channel. Complete full Word/PDF visual review, independent source/content review and a separate protocol under guide/06-review.md before delivery.')
        else:
            mode = '--artifacts' if data['changes'] else '--verify'
            check = execute(filler, [approved, mode, absolute(args.document), '--approved-sha256', digest,
                                    '--snapshot', work / 'snapshot.json'], work, '02-review')
            result = finish_report(work, release, 'artifacts_only' if data['changes'] else 'technical_checks_passed',
                                   data=str(approved), file=str(absolute(args.document)), check=check,
                                   next_step='Save check.saved_snapshot.sha256 separately. Full visual and independent review is still required by guide/06-review.md; an artifacts-only check does not verify the edits or contractual content.')
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return exit_code


def emit_error(errors):
    result = dict(ok=False, status='draft', ready_for_delivery=False, errors=errors,
                  work_directory=str(WORK_DIRECTORY) if WORK_DIRECTORY else None)
    if WORK_DIRECTORY:
        existing = []
        try:
            paths = sorted(WORK_DIRECTORY.iterdir())
        except OSError as exc:
            paths = []
            result['existing_files_read_error'] = str(exc)
        for path in paths:
            if path.is_file() and not path.is_symlink():
                try:
                    body = read_file(path, MAX_FILE)
                    existing.append(dict(path=str(path), size=len(body), sha256=sha(body)))
                except (OSError, ValueError) as exc:
                    existing.append(dict(path=str(path), read_error=str(exc)))
        result['existing_files'] = existing
        try:
            write_new(WORK_DIRECTORY / 'error.json', encoded(result))
            result['error_file'] = str(WORK_DIRECTORY / 'error.json')
        except OSError as exc:
            result['error_save_failed'] = str(exc)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    sys.dont_write_bytecode = True
    try:
        sys.exit(main())
    except Failure as exc:
        emit_error([exc.issue])
        sys.exit(1)
    except Exception as exc:
        emit_error([dict(code='WIZARD_ERROR', message=str(exc), next_step='Preserve the actual error and files. Do not change pins or manufacture evidence. Follow guide/08-errors.md.')])
        sys.exit(2)
