"""Fetch a pinned ThinkPair method or script over verified HTTPS. Python 3; no dependencies.

Never uploads workspace material. A failed request never falls back to a cache.
Supports both text/markdown (.md) and text/x-python (.py) assets, plus --sync for annual members.
Note: `expected_sha256` in connection.json verifies the remote `thinkpair.first_connection` markdown body,
NOT the SHA-256 of this `fetch_method.py` client script itself.
Verified Python scripts are also mirrored to `<cache-dir>/bin/<tool>.py` for versionless invocation.
"""
from pathlib import Path
import argparse
import datetime
import email.utils
import hashlib
import http.client
import json
import os
import re
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid


BASE_URL = 'https://thinkpair.cn/api'
METHOD_ID = 'thinkpair.first_connection'
SAFE_METHOD_ID = re.compile(r'thinkpair\.[a-z][a-z0-9_]{0,63}')
VALID_FORMATS = {'text/markdown': '.md', 'text/x-python': '.py'}
PYTHON_RUNNER_ALIASES = {
    'thinkpair.toolkit': 'tp_toolkit.py',
    'thinkpair.board_builder': 'build_board.py',
    'thinkpair.audit_web_free': 'audit_web_free.py',
    'thinkpair.audit_web_pro': 'audit_web_pro.py',
}
MAX_BYTES = 2 * 1024 * 1024
MAX_CATALOG_METHODS = 20
TIMEOUT_SECONDS = 15
REQUEST_ID = re.compile(r'[A-Za-z0-9_-]{8,80}')


class FetchError(Exception):
    """Only constant local error codes and sanitized retry timing leave this client."""

    def __init__(self, code, retry_after=None):
        super().__init__(code)
        self.code = code
        self.retry_after = retry_after


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise FetchError('redirect_rejected')


def validate_connection(config, *, allow_loopback=False):
    """Validate an issued or catalog-derived connection."""
    fields = ('base_url', 'method_id', 'version', 'expected_sha256', 'token')
    if not isinstance(config, dict) or not all(isinstance(config.get(k), str) for k in fields):
        raise FetchError('invalid_connection_schema')
    valid_url = config['base_url'] == BASE_URL
    if not valid_url and allow_loopback:
        match = re.fullmatch(r'http://127\.0\.0\.1:([1-9][0-9]{0,4})/api', config['base_url'])
        valid_url = bool(match and int(match.group(1)) <= 65535)
    if not valid_url:
        raise FetchError('connection_must_be_thinkpair_https')
    if not SAFE_METHOD_ID.fullmatch(config['method_id']) or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', config['version']):
        raise FetchError('invalid_method_identifier')
    if not re.fullmatch(r'[a-f0-9]{64}', config['expected_sha256']):
        raise FetchError('invalid_pinned_hash')
    token = config['token']
    if not 32 <= len(token) <= 512 or not token.isascii() or any(ord(c) <= 32 or ord(c) == 127 for c in token):
        raise FetchError('invalid_connection_credential')
    return {key: config[key] for key in fields}


def load_connection(path, *, allow_loopback=False):
    config = validate_connection(json.loads(Path(path).read_text(encoding='utf-8-sig')), allow_loopback=allow_loopback)
    if config['method_id'] != METHOD_ID:
        raise FetchError('bootstrap_connection_required')
    return config


def endpoint_for(config):
    query = urllib.parse.urlencode({'version': config['version']})
    return config['base_url'] + '/v1/methods/' + config['method_id'] + '?' + query


def atomic_write(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
    try:
        temporary.write_bytes(data)
        os.replace(temporary, path)
    finally:
        if temporary.exists():
            temporary.unlink()


def cache_paths(config, cache_dir, ext='.md'):
    folder = Path(cache_dir) / 'methods' / config['method_id']
    return folder / (config['version'] + ext), folder / (config['version'] + '.receipt.json')


def locate_cached_pair(config, cache_dir):
    md_doc, receipt_path = cache_paths(config, cache_dir, '.md')
    if md_doc.is_file():
        return md_doc, receipt_path, 'text/markdown'
    py_doc, _ = cache_paths(config, cache_dir, '.py')
    if py_doc.is_file():
        return py_doc, receipt_path, 'text/x-python'
    return md_doc, receipt_path, 'text/markdown'


def read_cache_bytes(path):
    """Bound the actual read even if a file grows after an earlier check."""
    with Path(path).open('rb') as stream:
        data = stream.read(MAX_BYTES + 1)
    if len(data) > MAX_BYTES:
        raise FetchError('cache_integrity_failed')
    return data


def commit_cache(document, receipt_path, body, receipt_data):
    """Stage both files before replacing either; restore the old body on a write error."""
    document.parent.mkdir(parents=True, exist_ok=True)
    marker = '.' + uuid.uuid4().hex + '.tmp'
    body_temp = document.with_name(document.name + marker)
    receipt_temp = receipt_path.with_name(receipt_path.name + marker)
    prior_body = read_cache_bytes(document) if document.exists() else None
    try:
        body_temp.write_bytes(body)
        receipt_temp.write_bytes(receipt_data)
        os.replace(body_temp, document)
        try:
            os.replace(receipt_temp, receipt_path)
        except OSError:
            if prior_body is None:
                document.unlink()
            else:
                atomic_write(document, prior_body)
            raise
    finally:
        for temporary in (body_temp, receipt_temp):
            if temporary.exists():
                temporary.unlink()


def verify_cached(config, cache_dir, *, allow_loopback=False):
    config = validate_connection(config, allow_loopback=allow_loopback)
    document, receipt_path, expected_format = locate_cached_pair(config, cache_dir)
    if not document.is_file() or not receipt_path.is_file():
        raise FetchError('verified_cache_not_found')
    try:
        body = read_cache_bytes(document)
        receipt = json.loads(read_cache_bytes(receipt_path).decode('utf-8'))
        if not isinstance(receipt, dict):
            raise FetchError('cache_integrity_failed')
        request_id = receipt.get('request_id')
        recorded_format = receipt.get('format', 'text/markdown')
        valid = (
            hashlib.sha256(body).hexdigest() == config['expected_sha256']
            and receipt.get('sha256') == config['expected_sha256']
            and receipt.get('method_id') == config['method_id']
            and receipt.get('version') == config['version']
            and receipt.get('api_version') == '1'
            and receipt.get('source') == 'https'
            and receipt.get('api_called') is True
            and receipt.get('endpoint') == endpoint_for(config)
            and receipt.get('bytes') == len(body)
            and recorded_format == expected_format
            and isinstance(request_id, str)
            and REQUEST_ID.fullmatch(request_id)
            and config['token'] not in request_id
        )
        if not valid:
            raise FetchError('cache_integrity_failed')
    except (ValueError, TypeError, UnicodeError, RecursionError):
        raise FetchError('cache_integrity_failed') from None
    return {
        'source': 'verified_local_cache', 'offline': True, 'api_called': False,
        'method_id': config['method_id'], 'version': config['version'], 'format': expected_format,
        'sha256': config['expected_sha256'], 'method_path': str(document.resolve()),
        'original_request_id': request_id, 'receipt_path': str(receipt_path.resolve()),
        'notice': '离线读取已校验缓存；本次未调用 API，也未验证凭证当前是否有效。',
    }


def unique_json_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise FetchError('invalid_method_catalog')
        result[key] = value
    return result


def reject_json_constant(value):
    raise FetchError('invalid_method_catalog')


def parse_method_catalog(body):
    """Read one inert, strictly shaped catalog; it cannot supply URLs or commands."""
    try:
        lines = body.decode('utf-8').splitlines()
        marker = '```thinkpair-method-catalog'
        starts = [index for index, line in enumerate(lines) if line.startswith(marker)]
        if not starts:
            raise FetchError('method_catalog_unavailable')
        if len(starts) != 1 or lines[starts[0]] != marker:
            raise FetchError('invalid_method_catalog')
        start = starts[0] + 1
        end = next((index for index in range(start, len(lines)) if lines[index] == '```'), None)
        if end is None:
            raise FetchError('invalid_method_catalog')
        catalog = json.loads('\n'.join(lines[start:end]), object_pairs_hook=unique_json_object,
                             parse_constant=reject_json_constant)
        if not isinstance(catalog, dict) or set(catalog) != {'schema_version', 'methods'}:
            raise FetchError('invalid_method_catalog')
        if type(catalog['schema_version']) is not int or catalog['schema_version'] != 1:
            raise FetchError('invalid_method_catalog')
        methods = catalog['methods']
        if not isinstance(methods, list) or not 1 <= len(methods) <= MAX_CATALOG_METHODS:
            raise FetchError('invalid_method_catalog')
        result = {}
        for method in methods:
            if not isinstance(method, dict) or set(method) != {'id', 'version', 'sha256'}:
                raise FetchError('invalid_method_catalog')
            if not all(isinstance(value, str) for value in method.values()):
                raise FetchError('invalid_method_catalog')
            if (not SAFE_METHOD_ID.fullmatch(method['id']) or method['id'] == METHOD_ID
                    or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', method['version'])
                    or not re.fullmatch(r'[a-f0-9]{64}', method['sha256'])
                    or method['id'] in result):
                raise FetchError('invalid_method_catalog')
            result[method['id']] = method
        return result
    except (ValueError, TypeError, UnicodeError, RecursionError):
        raise FetchError('invalid_method_catalog') from None


def select_method(config, cache_dir, method_id, *, allow_loopback=False):
    """Derive a child pin only from the administrator-pinned bootstrap cache."""
    config = validate_connection(config, allow_loopback=allow_loopback)
    if config['method_id'] != METHOD_ID:
        raise FetchError('bootstrap_connection_required')
    if not isinstance(method_id, str) or not SAFE_METHOD_ID.fullmatch(method_id):
        raise FetchError('invalid_method_identifier')
    verified = verify_cached(config, cache_dir, allow_loopback=True) if allow_loopback else verify_cached(config, cache_dir)
    body = read_cache_bytes(verified['method_path'])
    if hashlib.sha256(body).hexdigest() != config['expected_sha256']:
        raise FetchError('cache_integrity_failed')
    catalog = parse_method_catalog(body)
    if method_id not in catalog:
        raise FetchError('method_not_in_catalog')
    method = catalog[method_id]
    return validate_connection({**config, 'method_id': method['id'],
                                'version': method['version'], 'expected_sha256': method['sha256']},
                               allow_loopback=allow_loopback)


def parse_retry_after(value):
    if not isinstance(value, str) or len(value) > 80:
        return None
    if re.fullmatch(r'[0-9]{1,6}', value):
        return min(int(value), 86400)
    try:
        at = email.utils.parsedate_to_datetime(value)
        if at.tzinfo is None:
            return None
        delta = (at - datetime.datetime.now(datetime.timezone.utc)).total_seconds()
        return min(max(0, int(delta + 0.999)), 86400)
    except (ValueError, TypeError, OverflowError):
        return None


def http_failure(status, headers=None):
    if status == 401:
        return FetchError('credential_invalid_revoked_or_expired')
    if status == 429:
        retry_after = parse_retry_after(headers.get('Retry-After')) if headers else None
        return FetchError('rate_limited', retry_after=retry_after)
    if 500 <= status <= 599:
        return FetchError('service_busy')
    if 300 <= status <= 399:
        return FetchError('redirect_rejected')
    return FetchError('unexpected_http_status')


def open_json_get(url, token):
    req = urllib.request.Request(url, headers={
        'Authorization': 'Bearer ' + token, 'Accept': 'application/json',
    }, method='GET')
    opener = urllib.request.build_opener(
        urllib.request.ProxyHandler({}), NoRedirect(),
        urllib.request.HTTPSHandler(context=ssl.create_default_context()),
    )
    try:
        with opener.open(req, timeout=TIMEOUT_SECONDS) as response:
            if response.status != 200:
                raise http_failure(response.status, response.headers)
            if response.headers.get_content_type() != 'application/json':
                raise FetchError('unexpected_content_type')
            declared_length = response.headers.get('Content-Length')
            if declared_length is not None:
                if not re.fullmatch(r'[0-9]{1,12}', declared_length):
                    raise FetchError('invalid_response')
                if int(declared_length) > MAX_BYTES:
                    raise FetchError('response_too_large')
            raw = response.read(MAX_BYTES + 1)
            if len(raw) > MAX_BYTES:
                raise FetchError('response_too_large')
            ids = response.headers.get_all('X-Request-ID', [])
            response_id = ids[0] if len(ids) == 1 else None
            return raw, response_id
    except urllib.error.HTTPError as exc:
        failure = http_failure(exc.code, exc.headers)
        exc.close()
        raise failure from None
    except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException):
        raise FetchError('service_unavailable') from None


def fetch(config, cache_dir, *, allow_loopback=False):
    config = validate_connection(config, allow_loopback=allow_loopback)
    endpoint = endpoint_for(config)
    raw, response_id = open_json_get(endpoint, config['token'])
    try:
        payload = json.loads(raw.decode('utf-8'))
        if not isinstance(payload, dict) or not isinstance(payload.get('method'), dict):
            raise FetchError('invalid_response')
        method = payload['method']
        if not all(isinstance(method.get(key), str) for key in ('id', 'version', 'format', 'sha256', 'content')):
            raise FetchError('invalid_response')
        body = method['content'].encode('utf-8')
        actual_hash = hashlib.sha256(body).hexdigest()
        fmt = method['format']
        if payload['api_version'] != '1' or method['id'] != config['method_id'] or method['version'] != config['version'] or fmt not in VALID_FORMATS:
            raise FetchError('response_contract_mismatch')
        if actual_hash != method['sha256'] or actual_hash != config['expected_sha256']:
            raise FetchError('method_integrity_failed')
        if not response_id or payload['request_id'] != response_id or not REQUEST_ID.fullmatch(response_id) or config['token'] in response_id:
            raise FetchError('request_id_mismatch')
    except (KeyError, TypeError, ValueError, UnicodeError, RecursionError):
        raise FetchError('invalid_response') from None
    document, receipt_path = cache_paths(config, cache_dir, VALID_FORMATS[fmt])
    receipt = {
        'api_version': '1', 'source': 'https', 'offline': False, 'api_called': True,
        'method_id': method['id'], 'version': method['version'], 'format': fmt, 'sha256': actual_hash,
        'request_id': response_id,
        'retrieved_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
        'endpoint': endpoint, 'bytes': len(body),
    }
    commit_cache(document, receipt_path, body, json.dumps(receipt, ensure_ascii=False, indent=2).encode('utf-8'))
    out = {**receipt, 'method_path': str(document.resolve()), 'receipt_path': str(receipt_path.resolve())}
    if fmt == 'text/x-python':
        alias_name = PYTHON_RUNNER_ALIASES.get(method['id'], method['id'].split('.', 1)[-1] + '.py')
        runner_path = Path(cache_dir) / 'bin' / alias_name
        atomic_write(runner_path, body)
        out['runner_path'] = str(runner_path.resolve())
    return out


def sync_release(config, cache_dir, *, allow_loopback=False):
    """Sync latest published 2.63 Member assets over verified HTTPS."""
    config = validate_connection(config, allow_loopback=allow_loopback)
    if config['method_id'] != METHOD_ID:
        raise FetchError('bootstrap_connection_required')
    release_url = config['base_url'] + '/v1/releases/current'
    try:
        raw, response_id = open_json_get(release_url, config['token'])
    except FetchError as err:
        if err.code == 'unexpected_http_status':
            raise FetchError('tier_upgrade_required') from None
        raise
    try:
        payload = json.loads(raw.decode('utf-8'))
        if not isinstance(payload, dict) or payload.get('api_version') != '1' or payload.get('tier') != 'member':
            raise FetchError('invalid_response')
        if not response_id or payload.get('request_id') != response_id or not REQUEST_ID.fullmatch(response_id) or config['token'] in response_id:
            raise FetchError('request_id_mismatch')
        assets = payload.get('assets')
        if not isinstance(assets, list) or not 1 <= len(assets) <= 30:
            raise FetchError('invalid_response')
        validated_assets = []
        for item in assets:
            if not isinstance(item, dict) or not all(isinstance(item.get(k), str) for k in ('id', 'version', 'format', 'tier', 'sha256')):
                raise FetchError('invalid_response')
            if (not SAFE_METHOD_ID.fullmatch(item['id']) or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', item['version'])
                    or item['format'] not in VALID_FORMATS or not re.fullmatch(r'[a-f0-9]{64}', item['sha256'])):
                raise FetchError('invalid_response')
            validated_assets.append(item)
    except (KeyError, TypeError, ValueError, UnicodeError, RecursionError):
        raise FetchError('invalid_response') from None

    synced = []
    for item in validated_assets:
        asset_cfg = validate_connection({
            'base_url': config['base_url'],
            'method_id': item['id'],
            'version': item['version'],
            'expected_sha256': item['sha256'],
            'token': config['token'],
        }, allow_loopback=allow_loopback)
        try:
            cached = verify_cached(asset_cfg, cache_dir, allow_loopback=allow_loopback)
            if item['format'] == 'text/x-python':
                alias_name = PYTHON_RUNNER_ALIASES.get(item['id'], item['id'].split('.', 1)[-1] + '.py')
                atomic_write(Path(cache_dir) / 'bin' / alias_name, read_cache_bytes(cached['method_path']))
            synced.append({'id': item['id'], 'version': item['version'], 'status': 'already_current', 'path': cached['method_path']})
        except FetchError:
            fetched = fetch(asset_cfg, cache_dir, allow_loopback=allow_loopback)
            synced.append({'id': item['id'], 'version': item['version'], 'status': 'updated', 'path': fetched['method_path']})

    manifest_path = Path(cache_dir) / 'current-release.json'
    summary = {
        'source': 'https_sync',
        'api_called': True,
        'channel': str(payload.get('channel', '2.63')),
        'request_id': response_id,
        'synced_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
        'assets': synced,
    }
    atomic_write(manifest_path, json.dumps(summary, ensure_ascii=False, indent=2).encode('utf-8'))
    return {**summary, 'release_manifest_path': str(manifest_path.resolve())}


ERROR_MESSAGES = {
    'credential_invalid_revoked_or_expired': '凭证无效、已撤销或已到期，请联系发放者核对。',
    'rate_limited': '请求过于频繁，请稍后重试。',
    'service_busy': '服务暂时繁忙，请稍后重试。',
    'service_unavailable': '连接失败或超时，请检查网络及系统证书设置后重试。',
    'connection_must_be_thinkpair_https': '连接配置必须使用 https://thinkpair.cn/api。',
    'redirect_rejected': '已拒绝跳转，凭证不会转发到其他地址。',
    'bootstrap_connection_required': '连接文件必须保留发放的 first_connection 配置；后续方法请用 --method 选择。',
    'method_catalog_unavailable': '当前固定版本的启动方法不含后续方法目录；请联系发放者领取兼容配置，不会自动升级。',
    'invalid_method_catalog': '启动方法中的方法目录格式或内容不符合约定，已停止选择。',
    'method_not_in_catalog': '指定方法不在已验证的启动方法目录中。',
    'verified_cache_not_found': '未找到已验证缓存；请先正常获取相应方法。',
    'tier_upgrade_required': '当前凭证为免费基础版；持续升级通道与会员专属模块属年度会员权益，本地已有文件不受影响。',
    'unexpected_http_status': '请求未被允许（若使用的是免费版凭证，深度诊断台 Web、主流 Agent 专属提效与 365 格看板属年度会员专属权益，本地已有知识库不受影响）。',
}


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--connection', required=True, help='Administrator-issued connection JSON path')
    parser.add_argument('--cache-dir', required=True, help='Independent local workspace directory')
    parser.add_argument('--method', help='Exact ongoing method ID from the verified bootstrap catalog')
    parser.add_argument('--offline', action='store_true', help='Explicitly read verified local cache; does not call the API or check credential status')
    parser.add_argument('--sync', action='store_true', help='Sync all latest 2.63 Member assets from the release channel')
    parser.add_argument('--allow-loopback', action='store_true', help='Explicitly permit local 127.0.0.1 loopback server during local testing')
    args = parser.parse_args(argv)
    try:
        config = load_connection(args.connection, allow_loopback=args.allow_loopback)
        if args.sync:
            if args.offline or args.method is not None:
                raise FetchError('invalid_connection_schema')
            result = sync_release(config, args.cache_dir, allow_loopback=args.allow_loopback)
        else:
            if args.method is not None:
                config = select_method(config, args.cache_dir, args.method, allow_loopback=args.allow_loopback)
            result = (
                verify_cached(config, args.cache_dir, allow_loopback=args.allow_loopback)
                if args.offline
                else fetch(config, args.cache_dir, allow_loopback=args.allow_loopback)
            )
        print(json.dumps(result, ensure_ascii=False, indent=2))
    except (FetchError, OSError, ValueError, KeyError, RecursionError) as exc:
        code = exc.code if isinstance(exc, FetchError) else 'local_configuration_or_file_error'
        error = {'status': 'error', 'code': code, 'cache_fallback': False,
                 'message': ERROR_MESSAGES.get(code, '获取或校验失败；本次未使用缓存替代联网结果。')}
        if isinstance(exc, FetchError) and exc.retry_after is not None:
            error['retry_after'] = exc.retry_after
        print(json.dumps(error, ensure_ascii=False), file=sys.stderr)
        return 1
    return 0


if __name__ == '__main__':
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8')
        sys.stderr.reconfigure(encoding='utf-8')
    raise SystemExit(main())
