"""Single-shot portal upload (semantic port of the IDBManager uploader). No state, no retries.

Outcome contract: ``not_sent`` only when the failure is certain to precede STOR (config, connect,
login, TLS, PROT P); ``unknown`` from the moment STOR is attempted, including data-channel errors
inside ``storbinary`` and an uncertain Domiporta rename; ``confirmed`` after a 2xx STOR (and, for
Domiporta, after the rename to ``ok-``). A close error after confirmation never undoes it.
Results carry whitelisted error codes only: never exception text, hosts, ports or credentials.
FTPS (kept per D07) always uses a verifying context and PROT P; no active profile uses it.
"""
from dataclasses import dataclass, field
import ftplib
import io
import re
import socket
import ssl
import time

from . import export_arm
from . import export_transport_config as config

ERROR_CODES = {'connect_failed', 'login_failed', 'tls_failed', 'stor_failed', 'rename_failed', 'timeout',
               'config_missing', 'config_invalid', 'arm_refused', 'unknown'}
_NAME = re.compile(r'^[A-Za-z0-9_.-]{1,120}\.zip$')


@dataclass
class UploadResult:
    outcome: str                      # not_sent | unknown | confirmed
    phase: str                        # last phase reached
    bytes_sent: int = 0               # bytes handed to the socket callback, not proof of storage
    bytes_complete: bool = False
    stor_reply_code: object = None
    rename_reply_code: object = None
    timings: dict = field(default_factory=dict)
    error_code: object = None


def tls_context():
    """Verifying client context (certificate chain + hostname)."""
    context = ssl.create_default_context()
    assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname
    return context


def _code(reply):
    try:
        return int(str(reply)[:3])
    except (TypeError, ValueError):
        return None


def _classify(exc, phase):
    if isinstance(exc, (ssl.SSLError, ssl.CertificateError)):
        return 'tls_failed'
    if isinstance(exc, (socket.timeout, TimeoutError)):
        return 'timeout'
    return {'connect': 'connect_failed', 'login': 'login_failed', 'prot_p': 'tls_failed',
            'stor': 'stor_failed', 'rename': 'rename_failed'}.get(phase, 'unknown')


def upload_portal_zip(profile, zip_filename, zip_bytes, *, secret_getter=config.environment_getter,
                      ftp_factory=None, ssl_context=None, clock=time.perf_counter):
    """Upload ``zip_bytes`` once. Never raises for transport problems; interrupts are the caller's problem.

    The transport arm is checked FIRST: without a valid, unexpired exports-arm.json that allows this profile nothing is
    created (no config read, no ftp object, no socket) and the result is ``not_sent`` / ``arm_refused``.
    """
    result = UploadResult('not_sent', 'arm')
    verdict = export_arm.check(profile)
    if not verdict['allowed']:
        export_arm.refuse(profile, verdict['code'])
        result.error_code = 'arm_refused'
        return result
    result.phase = 'config'
    if not isinstance(zip_filename, str) or not _NAME.fullmatch(zip_filename) or '..' in zip_filename:
        result.error_code = 'config_invalid'
        return result
    if not isinstance(zip_bytes, (bytes, bytearray)) or not zip_bytes:
        result.error_code = 'config_invalid'
        return result
    try:
        settings = config.load_profile(profile, secret_getter)
    except config.ConfigError as exc:
        result.error_code = exc.code
        return result
    if ftp_factory is not None:
        ftp = ftp_factory(settings)
    elif settings.use_tls:
        ftp = ftplib.FTP_TLS(context=ssl_context or tls_context())
    else:
        ftp = ftplib.FTP()
    phase = 'connect'
    marks = result.timings

    def stage(name, started):
        marks[name] = {'seconds': max(0.0, clock() - started), 'complete': True}
    try:
        started = clock()
        ftp.connect(host=settings.host, port=settings.port, timeout=settings.timeout_seconds)
        stage('connect', started)
        phase = 'login'
        started = clock()
        ftp.login(user=settings.username, passwd=settings.password)
        stage('login', started)
        if settings.use_tls:
            phase = 'prot_p'
            ftp.prot_p()
        ftp.set_pasv(True)                       # client-side flag only; keeps the passive data channel
        phase = 'stor'
        result.outcome, result.phase = 'unknown', 'stor'     # from here a failure may have reached the server
        sent = [0]

        def counted(block):
            sent[0] += len(block)
            result.bytes_sent = sent[0]
        started = clock()
        try:
            reply = ftp.storbinary('STOR ' + zip_filename, io.BytesIO(bytes(zip_bytes)), callback=counted)
        finally:
            marks['stor'] = {'seconds': max(0.0, clock() - started), 'complete': False}
        marks['stor']['complete'] = True
        result.stor_reply_code = _code(reply)
        result.bytes_complete = sent[0] == len(zip_bytes)
        if settings.ready_prefix:
            phase = 'rename'
            result.phase = 'rename'
            started = clock()
            try:
                rename_reply = ftp.rename(zip_filename, settings.ready_prefix + zip_filename)
            finally:
                marks['rename'] = {'seconds': max(0.0, clock() - started), 'complete': False}
            marks['rename']['complete'] = True
            result.rename_reply_code = _code(rename_reply)
        result.outcome, result.phase = 'confirmed', 'done'
    except Exception as exc:                      # includes ftplib.all_errors, OSError and ssl errors
        result.error_code = _classify(exc, phase)
        result.phase = phase
    try:
        if result.outcome == 'confirmed':
            try:
                ftp.quit()
            except Exception:
                pass
    finally:
        try:
            if getattr(ftp, 'sock', None) is not None:
                ftp.close()
        except Exception:
            pass
    return result
