"""mitmdump addon. Stream traffic unchanged; retain bounded previews and metadata."""

import asyncio
import functools
import ipaddress
import json
import os
from pathlib import Path
import re
import tempfile
import time
from urllib.parse import unquote, urlsplit
import zlib


SECRET = re.compile(r'authorization|cookie|token|secret|password|passwd|api.?key|credential|session|jwt|bearer|signature|^pwd$', re.I)
OPAQUE = re.compile(r'^[A-Za-z0-9_+=.-]{24,}$')
BEARER = re.compile(r'\b(?:Bearer|Basic)\s+\S+|\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', re.I)
MAX_BODY = 16_384


def clean_value(value, depth=0):
    if depth > 8:
        return '[TRUNCATED]'
    if isinstance(value, dict):
        return {str(k)[:100]: '[REDACTED]' if SECRET.search(str(k)) else clean_value(v, depth + 1)
                for k, v in list(value.items())[:100]}
    if isinstance(value, list):
        return [clean_value(v, depth + 1) for v in value[:100]]
    if isinstance(value, str):
        if len(value) > 1000:
            return '[TRUNCATED]'
        if value.startswith(('https://', 'http://')):
            return safe_url(value)
        return BEARER.sub('[REDACTED]', value)
    return value


def safe_url(url):
    parts = urlsplit(url)
    host = parts.hostname or ''
    segments = (parts.path or '/').split('/')
    redact_next = False
    for index, segment in enumerate(segments):
        decoded = unquote(unquote(segment))
        sensitive = bool(SECRET.search(decoded))
        if redact_next or sensitive or OPAQUE.fullmatch(decoded):
            segments[index] = '[REDACTED]'
        redact_next = sensitive
    authority = f'[{host}]' if ':' in host else host
    authority += f':{parts.port}' if parts.port else ''
    return f'{parts.scheme}://{authority}{"/".join(segments)}'[:2000]


def host_matches(host, selected):
    host = host.rstrip('.').lower()
    if not selected:
        return True
    try:
        selected_ip = ipaddress.ip_address(selected)
    except ValueError:
        return host == selected or host.endswith('.' + selected)
    try:
        return ipaddress.ip_address(host) == selected_ip
    except ValueError:
        return False


def error_kind(error):
    message = str(error).lower()
    for kind, terms in (
        ('tls', ('tls', 'ssl', 'certificate')),
        ('dns', ('dns', 'resolve', 'name lookup')),
        ('timeout', ('timeout', 'timed out')),
        ('connect', ('connect', 'refused', 'unreachable')),
    ):
        if any(term in message for term in terms):
            return kind
    return 'proxy'


def json_body(preview, complete):
    if not complete:
        return '[OMITTED: incomplete body]'
    content_type = preview['type']
    if not (content_type == 'application/json' or content_type.endswith('+json')):
        return None
    raw = bytes(preview['data'])
    if len(raw) > MAX_BODY:
        return '[OMITTED: body exceeds limit]'
    try:
        encoding = preview['encoding']
        if encoding in ('gzip', 'deflate'):
            decoder = zlib.decompressobj(31 if encoding == 'gzip' else 15)
            raw = decoder.decompress(raw, MAX_BODY + 1)
            if len(raw) > MAX_BODY or decoder.unconsumed_tail:
                return '[OMITTED: decoded body exceeds limit]'
            if not decoder.eof or decoder.unused_data:
                return '[OMITTED: invalid compressed body]'
        elif encoding not in ('', 'identity'):
            return '[OMITTED: unsupported content encoding]'
        return clean_value(json.loads(raw))
    except (UnicodeError, ValueError, RecursionError, zlib.error):
        return '[OMITTED: invalid JSON body]'


def guarded(method):
    @functools.wraps(method)
    def wrapped(self, *args):
        try:
            return method(self, *args)
        except Exception as exc:
            # mitmproxy otherwise logs addon errors and can keep serving, making
            # an empty capture appear successful. Publish a fail-closed status.
            self.stats['error'] = 'addon_' + type(exc).__name__
            try:
                self.save_status()
            finally:
                from mitmproxy import ctx
                ctx.master.shutdown()
    return wrapped


class Capture:
    def __init__(self):
        self.stats = {'ready': False, 'finished': False, 'flows': 0, 'records': 0,
                      'bytes': 0, 'incomplete': 0, 'truncated': False, 'error': None}
        self.active = {}
        self.file = None
        self.watcher = None

    def save_status(self):
        with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=self.status.parent,
                                         prefix='.capture-status-', delete=False) as file:
            temporary = Path(file.name)
            json.dump(self.stats, file)
        try:
            os.replace(temporary, self.status)
        finally:
            temporary.unlink(missing_ok=True)

    @guarded
    def running(self):
        self.status = Path(os.environ['NETWORK_CAPTURE_STATUS'])
        self.selected = os.environ.get('NETWORK_CAPTURE_HOST', '')
        self.include_bodies = os.environ.get('NETWORK_CAPTURE_JSON_BODIES') == '1'
        self.max_flows = int(os.environ['NETWORK_CAPTURE_MAX_FLOWS'])
        self.max_bytes = int(os.environ['NETWORK_CAPTURE_MAX_BYTES'])
        flags = os.O_WRONLY | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0)
        self.file = os.fdopen(os.open(os.environ['NETWORK_CAPTURE_OUTPUT'], flags), 'ab', buffering=0)
        self.stats['ready'] = True
        self.save_status()
        self.watcher = asyncio.create_task(self.watch_stop())

    async def watch_stop(self):
        from mitmproxy import ctx
        stop = Path(os.environ['NETWORK_CAPTURE_STOP'])
        while not stop.exists():
            await asyncio.sleep(0.1)
        ctx.master.shutdown()

    def write(self, row):
        encoded = (json.dumps({'schema_version': 1, **row}, ensure_ascii=False) + '\n').encode()
        if self.stats['bytes'] + len(encoded) > self.max_bytes:
            self.stats['truncated'] = True
            self.save_status()
            return
        self.file.write(encoded)
        self.stats['records'] += 1
        self.stats['bytes'] += len(encoded)
        self.save_status()

    def preview(self, message, state, direction):
        content_type = message.headers.get('content-type', '').split(';')[0].strip().lower()[:100]
        state['row'][direction + '_content_type'] = content_type
        state[direction] = {'data': bytearray(), 'type': content_type,
                            'encoding': message.headers.get('content-encoding', '').lower().strip()}
        def stream(chunk):
            state['row'][direction + '_bytes'] += len(chunk)
            if self.include_bodies:
                data = state[direction]['data']
                data.extend(chunk[:max(0, MAX_BODY + 1 - len(data))])
            return chunk
        message.stream = stream

    @guarded
    def requestheaders(self, flow):
        # Stream even excluded/unrecorded traffic, so a large download does not
        # accumulate in mitmdump merely because it used this proxy.
        flow.request.stream = True
        if not host_matches(flow.request.host, self.selected):
            return
        if self.stats['flows'] >= self.max_flows:
            self.stats['truncated'] = True
            self.save_status()
            return
        self.stats['flows'] += 1
        row = {'kind': 'http', 'id': flow.id, 'method': flow.request.method,
               'url': safe_url(flow.request.url), 'host': flow.request.host,
               'timestamp_start': flow.request.timestamp_start,
               'status': None, 'request_bytes': 0, 'response_bytes': 0,
               'error': None, 'websocket_messages': 0,
               'websocket_client_bytes': 0, 'websocket_server_bytes': 0}
        state = {'row': row, 'request_complete': False, 'response_complete': False}
        self.active[flow.id] = state
        self.preview(flow.request, state, 'request')

    @guarded
    def request(self, flow):
        state = self.active.get(flow.id)
        if state:
            state['request_complete'] = True

    @guarded
    def responseheaders(self, flow):
        flow.response.stream = True
        state = self.active.get(flow.id)
        if state:
            state['row']['status'] = flow.response.status_code
            self.preview(flow.response, state, 'response')

    def finish(self, flow_id, event, complete, timestamp=None, keep=False):
        state = self.active.get(flow_id)
        if not state:
            return
        row = dict(state['row'])
        row.update(event=event, complete=complete,
                   duration_ms=round(max(0, (timestamp or time.time()) - row['timestamp_start']) * 1000, 1))
        if self.include_bodies:
            for direction in ('request', 'response'):
                row[direction + '_json'] = (json_body(state[direction], state[direction + '_complete'])
                                           if direction in state else None)
        self.write(row)
        if not keep:
            self.active.pop(flow_id)

    @guarded
    def response(self, flow):
        state = self.active.get(flow.id)
        if state:
            state['response_complete'] = True
            if flow.response.status_code == 101 and flow.response.headers.get('upgrade', '').lower() == 'websocket':
                self.finish(flow.id, 'websocket_open', False, flow.response.timestamp_end, keep=True)
            else:
                self.finish(flow.id, 'response', True, flow.response.timestamp_end)

    @guarded
    def error(self, flow):
        state = self.active.get(flow.id)
        if state:
            state['row']['error'] = error_kind(flow.error)
            self.finish(flow.id, 'error', True)

    @guarded
    def websocket_message(self, flow):
        message = flow.websocket.messages[-1]
        state = self.active.get(flow.id)
        if state:
            state['row']['websocket_messages'] += 1
            key = 'websocket_client_bytes' if message.from_client else 'websocket_server_bytes'
            state['row'][key] += len(message.content)
        # Keep the current message intact for forwarding; discard older payloads.
        del flow.websocket.messages[:-1]

    @guarded
    def websocket_end(self, flow):
        state = self.active.get(flow.id)
        if state:
            state['row']['websocket_close_code'] = flow.websocket.close_code
            self.finish(flow.id, 'websocket_end', True, flow.websocket.timestamp_end)

    def tls_error(self, data, side):
        address = data.context.server.address
        host = address[0] if address else (data.conn.sni or '')
        if host_matches(host, self.selected):
            self.write({'kind': 'connection_error', 'id': str(data.conn.id),
                        'event': 'tls_failed_' + side, 'host': host, 'error': 'tls', 'complete': True})

    @guarded
    def tls_failed_client(self, data):
        self.tls_error(data, 'client')

    @guarded
    def tls_failed_server(self, data):
        self.tls_error(data, 'server')

    @guarded
    def done(self):
        if not self.file:
            return
        self.stats['incomplete'] = len(self.active)
        for flow_id in list(self.active):
            self.finish(flow_id, 'capture_end', False)
        self.file.close()
        self.stats['finished'] = True
        self.save_status()


addons = [Capture()]
