"""X 2FA otomatizasyonu için çok iş parçacıklı istemci."""
from __future__ import annotations

import asyncio
import base64
import hashlib
import hmac
import inspect
import json
import logging
import os
import random
import threading
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List
from urllib.parse import parse_qs, urlparse

from tid_provider import TransactionIdError, TransactionIdProvider
from tls_client_manager import TLSClient, TLSClientConfigError

LOGGER = logging.getLogger("x_2fa.main")


@dataclass(slots=True)
class Config:
    """config.json içeriğini temsil eden küçük taşıyıcı."""

    threads: int
    proxy_raw: str
    user_agent: str
    request_timeout: int
    txid_timeout: int


@dataclass(slots=True)
class Account:
    """DataUsers.txt satırlarından elde edilen hesap verileri."""

    username: str
    password: str
    email: str
    auth_token: str
    ct0: str


@dataclass(slots=True)
class RunMetrics:
    success: int
    error: int
    lock: asyncio.Lock

    async def add_success(self) -> None:
        async with self.lock:
            self.success += 1

    async def add_error(self) -> None:
        async with self.lock:
            self.error += 1


@dataclass(slots=True)
class _RequestContext:
    """TransactionIdProvider'ın beklediği sade oturum kabuğu."""

    session: Any


def _configure_logging() -> None:
    """Terminalde okunabilir log formatı hazırla."""

    handler = logging.StreamHandler()
    formatter = logging.Formatter(
        "%(asctime)s | %(levelname)-7s | %(message)s",
        "%H:%M:%S",
    )
    handler.setFormatter(formatter)
    root_logger = logging.getLogger()
    root_logger.handlers.clear()
    root_logger.addHandler(handler)
    root_logger.setLevel(logging.INFO)


def _load_config(config_path: Path) -> Config:
    """config.json'u oku, beklenen anahtarları doğrula."""

    if not config_path.exists():
        raise SystemExit(f"config dosyası bulunamadı: {config_path}")
    try:
        raw_data = json.loads(config_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        raise SystemExit(f"config.json çözümlenemedi: {exc}") from exc

    try:
        threads = int(raw_data["threads"])
        proxy_raw = str(raw_data["proxy"]).strip()
        user_agent = str(raw_data["user_agent"]).strip()
        request_timeout = int(raw_data.get("request_timeout", 30))
        txid_timeout = int(raw_data.get("txid_timeout", 20))
    except KeyError as exc:
        raise SystemExit(f"config.json anahtar eksik: {exc.args[0]}") from exc
    except (TypeError, ValueError) as exc:
        raise SystemExit(f"config.json değeri geçersiz: {exc}") from exc

    if threads < 1:
        raise SystemExit("threads değeri en az 1 olmalı.")
    if not proxy_raw:
        raise SystemExit("proxy alanı boş olamaz.")
    if not user_agent:
        raise SystemExit("user_agent alanı boş olamaz.")

    if request_timeout < 1:
        raise SystemExit("request_timeout değeri en az 1 olmalı.")
    if txid_timeout < 1:
        raise SystemExit("txid_timeout değeri en az 1 olmalı.")

    return Config(
        threads=threads,
        proxy_raw=proxy_raw,
        user_agent=user_agent,
        request_timeout=request_timeout,
        txid_timeout=txid_timeout,
    )


def _parse_accounts(data_path: Path) -> List[Account]:
    """DataUsers.txt içindeki satırları hesap nesnelerine dönüştür."""

    if not data_path.exists():
        raise SystemExit(f"DataUsers.txt bulunamadı: {data_path}")

    accounts: List[Account] = []
    for line_no, raw_line in enumerate(data_path.read_text(encoding="utf-8").splitlines(), start=1):
        line = raw_line.strip()
        if not line:
            continue
        parts = line.split(":")
        if len(parts) < 4:
            LOGGER.warning("Line skipped (format error) [line %s]: %s", line_no, line)
            continue
        username, password, email, *rest = parts
        filtered = [segment.strip() for segment in rest if segment.strip()]
        if len(filtered) < 2:
            LOGGER.warning("Line skipped (missing ct0/auth_token) [line %s]: %s", line_no, line)
            continue
        token_a = filtered[-2]
        token_b = filtered[-1]
        # auth_token is typically shorter; ct0 is longer
        if len(token_a) <= len(token_b):
            auth_token, ct0 = token_a, token_b
        else:
            auth_token, ct0 = token_b, token_a
        if not auth_token or not ct0:
            LOGGER.warning("Line skipped (auth_token/ct0 missing) [line %s]", line_no)
            continue
        account = Account(
            username=username.strip(),
            password=password.strip(),
            email=email.strip(),
            auth_token=auth_token,
            ct0=ct0,
        )
        accounts.append(account)
    return accounts


def _normalize_proxy(raw: str) -> str:
    """ip:port:user:pass formatındaki proxy bilgisini tam URL'ye çevir."""

    cleaned = raw.strip()
    if cleaned.startswith("http://") or cleaned.startswith("https://"):
        return cleaned
    segments = cleaned.split(":")
    if len(segments) < 4:
        raise ValueError("proxy formatı ip:port:user:pass şeklinde olmalı")
    host, port, user, *password_parts = segments
    password = ":".join(password_parts)
    if not (host and port and user and password):
        raise ValueError("proxy bilgilerinden biri boş görünüyor")
    return f"http://{user}:{password}@{host}:{port}"


def _apply_proxy(session: Any, proxy_url: str) -> None:
    """Proxy ayarını hem oturuma hem de ortama uygula."""

    proxies = {"http": proxy_url, "https": proxy_url}
    if hasattr(session, "proxies") and isinstance(getattr(session, "proxies"), dict):
        session.proxies.update(proxies)
    else:
        LOGGER.warning("session.proxies not available; using environment variables only")
    os.environ["HTTP_PROXY"] = proxy_url
    os.environ["HTTPS_PROXY"] = proxy_url


def _shuffle_headers(headers: Dict[str, str]) -> Dict[str, str]:
    """Header sıralamasını rastgele değiştirerek anti-bot kontrollerine ufak çeşitlilik katar."""

    items = list(headers.items())
    random.shuffle(items)
    return dict(items)


def _create_tls_session(*, async_mode: bool = False) -> Any:
    """TLSClient üzerinden yeni bir session üret."""

    client = TLSClient(async_mode=async_mode)
    if client.session is None:
        raise RuntimeError("TLSClient session nesnesi döndürmedi")
    return client.session


def _set_auth_cookies(session: Any, account: Account) -> None:
    """auth_token ve ct0 değerlerini çerez olarak oturuma yaz."""

    session.cookies.set("auth_token", account.auth_token, domain=".x.com", path="/")
    session.cookies.set("ct0", account.ct0, domain=".x.com", path="/")


def _build_request_components(
    *, account: Account, user_agent: str, transaction_id: str
) -> Dict[str, Any]:
    """İstek için url, params, payload ve headerları tek pakette döndür."""

    url = "https://api.x.com/1.1/onboarding/task.json"
    params = {"flow_name": "two-factor-auth-app-enrollment"}
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "en-US",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/json",
            "origin": "https://x.com",
            "referer": "https://x.com/",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": user_agent,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "X-Twitter-Auth-Type": "OAuth2Session",
            "x-twitter-client-language": "en",
            "X-Client-Transaction-Id": transaction_id,
        }
    )
    payload = {
        "input_flow_data": {
            "flow_context": {
                "debug_overrides": {},
                "start_location": {"location": "settings"},
            }
        },
        "subtask_versions": {
            "action_list": 2,
            "alert_dialog": 1,
            "app_download_cta": 1,
            "check_logged_in_account": 1,
            "choice_selection": 3,
            "contacts_live_sync_permission_prompt": 0,
            "cta": 7,
            "email_verification": 2,
            "end_flow": 1,
            "enter_date": 1,
            "enter_email": 2,
            "enter_password": 5,
            "enter_phone": 2,
            "enter_recaptcha": 1,
            "enter_text": 5,
            "enter_username": 2,
            "generic_urt": 3,
            "in_app_notification": 1,
            "interest_picker": 3,
            "js_instrumentation": 1,
            "menu_dialog": 1,
            "notifications_permission_prompt": 2,
            "open_account": 2,
            "open_home_timeline": 1,
            "open_link": 1,
            "phone_verification": 4,
            "privacy_options": 1,
            "security_key": 3,
            "select_avatar": 4,
            "select_banner": 2,
            "settings_list": 7,
            "show_code": 1,
            "sign_up": 2,
            "sign_up_review": 4,
            "tweet_selection_urt": 1,
            "update_users": 1,
            "upload_media": 1,
            "user_recommendations_list": 4,
            "user_recommendations_urt": 1,
            "wait_spinner": 3,
            "web_modal": 1,
        },
    }
    return {"url": url, "params": params, "headers": headers, "payload": payload}


def _truncate_text(value: str, limit: int = 4000) -> str:
    if len(value) <= limit:
        return value
    return f"{value[:limit]}... [truncated {len(value) - limit} chars]"


def _log_step(
    worker_name: str,
    step: str,
    status: str,
    detail: str | None = None,
    *,
    level: int = logging.INFO,
) -> None:
    if detail:
        LOGGER.log(level, "%s | %-12s | %-7s | %s", worker_name, step, status, detail)
    else:
        LOGGER.log(level, "%s | %-12s | %-7s", worker_name, step, status)


def _get_worker_name() -> str:
    try:
        task = asyncio.current_task()
    except RuntimeError:
        task = None
    if task and task.get_name():
        return task.get_name()
    return threading.current_thread().name


def _generate_transaction_id(provider: TransactionIdProvider, path: str) -> str:
    return provider.generate("POST", path)


async def _read_response_text(response: Any) -> str:
    text_async = getattr(response, "text_async", None)
    if callable(text_async):
        try:
            result = text_async()
            if inspect.isawaitable(result):
                result = await result
            if result is None:
                return ""
            return str(result)
        except Exception:
            return ""

    content_async = getattr(response, "content_async", None)
    if callable(content_async):
        try:
            result = content_async()
            if inspect.isawaitable(result):
                result = await result
            if result is None:
                return ""
            if isinstance(result, (bytes, bytearray)):
                return bytes(result).decode("utf-8", "replace")
            return str(result)
        except Exception:
            return ""

    text_attr = getattr(response, "text", None)
    if text_attr is None:
        return ""
    try:
        if callable(text_attr):
            result = text_attr()
            if inspect.isawaitable(result):
                result = await result
        else:
            result = text_attr
        if result is None:
            return ""
        return str(result)
    except Exception:
        return ""


def _extract_flow_data(body_text: str) -> tuple[str, str]:
    if not body_text:
        return "", ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return "", ""
    flow_token = str(payload.get("flow_token") or "").strip()
    subtask_id = ""
    subtasks = payload.get("subtasks")
    if isinstance(subtasks, list):
        for subtask in subtasks:
            if isinstance(subtask, dict) and "enter_password" in subtask:
                subtask_id = str(subtask.get("subtask_id") or "").strip()
                break
    return flow_token, subtask_id


def _extract_flow_token(body_text: str) -> str:
    if not body_text:
        return ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return ""
    return str(payload.get("flow_token") or "").strip()


def _is_account_locked(body_text: str) -> bool:
    if not body_text:
        return False
    try:
        payload = json.loads(body_text)
    except Exception:
        return False
    errors = payload.get("errors")
    if not isinstance(errors, list):
        return False
    for error in errors:
        if not isinstance(error, dict):
            continue
        code = error.get("code")
        message = str(error.get("message") or "").lower()
        if code == 326 or "temporarily locked" in message:
            return True
    return False


def _parse_otpauth_secret(code: str) -> str:
    try:
        parsed = urlparse(code)
    except Exception:
        return ""
    query = parse_qs(parsed.query)
    secret = query.get("secret", [""])[0]
    return str(secret or "").strip()


def _extract_totp_secret(body_text: str) -> str:
    if not body_text:
        return ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return ""
    subtasks = payload.get("subtasks")
    if not isinstance(subtasks, list):
        return ""
    fallback_secret = ""
    for subtask in subtasks:
        if not isinstance(subtask, dict):
            continue
        show_code = subtask.get("show_code")
        if not isinstance(show_code, dict):
            continue
        code_value = show_code.get("code")
        if not code_value:
            continue
        code_text = str(code_value)
        if code_text.startswith("otpauth://"):
            secret = _parse_otpauth_secret(code_text)
            if secret:
                return secret
        if not fallback_secret:
            fallback_secret = code_text.strip()
    return fallback_secret


def _extract_backup_code(body_text: str) -> str:
    if not body_text:
        return ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return ""
    subtasks = payload.get("subtasks")
    if not isinstance(subtasks, list):
        return ""
    for subtask in subtasks:
        if not isinstance(subtask, dict):
            continue
        cta = subtask.get("cta")
        if not isinstance(cta, dict):
            continue
        secondary_text = cta.get("secondary_text")
        if not isinstance(secondary_text, dict):
            continue
        text = secondary_text.get("text")
        if not text:
            continue
        for line in str(text).splitlines():
            candidate = line.strip()
            if 6 <= len(candidate) <= 24 and candidate.isalnum():
                return candidate
    return ""


def _normalize_base32(secret: str) -> str:
    cleaned = secret.replace(" ", "").replace("-", "").strip()
    cleaned = "".join(ch for ch in cleaned if ch.isalnum())
    padding = (-len(cleaned)) % 8
    if padding:
        cleaned += "=" * padding
    return cleaned.upper()


def _generate_totp(secret: str, *, digits: int = 6, time_step: int = 30) -> str:
    if not secret:
        raise ValueError("TOTP secret missing")
    normalized = _normalize_base32(secret)
    try:
        key = base64.b32decode(normalized, casefold=True)
    except Exception as exc:
        raise ValueError("TOTP secret invalid") from exc
    counter = int(time.time()) // time_step
    msg = counter.to_bytes(8, "big")
    digest = hmac.new(key, msg, hashlib.sha1).digest()
    offset = digest[-1] & 0x0F
    code_int = int.from_bytes(digest[offset:offset + 4], "big") & 0x7FFFFFFF
    code = code_int % (10 ** digits)
    return f"{code:0{digits}d}"


def _build_password_subtask_components(
    *,
    account: Account,
    user_agent: str,
    transaction_id: str,
    flow_token: str,
    subtask_id: str,
) -> Dict[str, Any]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "en-US",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/json",
            "origin": "https://x.com",
            "referer": "https://x.com/",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": user_agent,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "X-Twitter-Auth-Type": "OAuth2Session",
            "x-twitter-client-language": "en",
            "X-Client-Transaction-Id": transaction_id,
        }
    )
    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": subtask_id or "TwoFactorEnrollmentVerifyPasswordSubtask",
                "enter_password": {
                    "password": account.password,
                    "link": "next_link",
                },
            }
        ],
    }
    return {"url": url, "headers": headers, "payload": payload}


def _build_auth_app_begin_components(
    *,
    account: Account,
    user_agent: str,
    transaction_id: str,
    flow_token: str,
) -> Dict[str, Any]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "en-US",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/json",
            "origin": "https://x.com",
            "referer": "https://x.com/",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": user_agent,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "X-Twitter-Auth-Type": "OAuth2Session",
            "x-twitter-client-language": "en",
            "X-Client-Transaction-Id": transaction_id,
        }
    )
    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "TwoFactorEnrollmentAuthenticationAppBeginSubtask",
                "action_list": {"link": "next_link"},
            }
        ],
    }
    return {"url": url, "headers": headers, "payload": payload}


def _build_auth_app_confirm_components(
    *,
    account: Account,
    user_agent: str,
    transaction_id: str,
    flow_token: str,
    totp_code: str,
) -> Dict[str, Any]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "en-US",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/json",
            "origin": "https://x.com",
            "referer": "https://x.com/",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": user_agent,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "X-Twitter-Auth-Type": "OAuth2Session",
            "x-twitter-client-language": "en",
            "X-Client-Transaction-Id": transaction_id,
        }
    )
    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "TwoFactorEnrollmentAuthenticationAppQrCodeSubtask",
                "show_code": {"link": "next_link"},
            },
            {
                "subtask_id": "TwoFactorEnrollmentAuthenticationAppEnterCodeSubtask",
                "enter_text": {"text": totp_code, "link": "next_link"},
            },
        ],
    }
    return {"url": url, "headers": headers, "payload": payload}


def _build_auth_app_complete_components(
    *,
    account: Account,
    user_agent: str,
    transaction_id: str,
    flow_token: str,
) -> Dict[str, Any]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "en-US",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/json",
            "origin": "https://x.com",
            "referer": "https://x.com/",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": user_agent,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "X-Twitter-Auth-Type": "OAuth2Session",
            "x-twitter-client-language": "en",
            "X-Client-Transaction-Id": transaction_id,
        }
    )
    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "TwoFactorEnrollmentAuthenticationAppCompleteSubtask",
                "cta": {"link": "finish_link"},
            }
        ],
    }
    return {"url": url, "headers": headers, "payload": payload}


async def _append_output_line(
    output_path: Path,
    account: Account,
    totp_secret: str,
    lock: asyncio.Lock,
) -> None:
    line = (
        f"{account.username}:{account.password}:{account.email}:"
        f"{account.ct0}:{account.auth_token}:{totp_secret}\n"
    )

    def _write_line() -> None:
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with output_path.open("a", encoding="utf-8") as handle:
            handle.write(line)

    async with lock:
        await asyncio.to_thread(_write_line)


async def _append_locked_line(
    locked_path: Path,
    account: Account,
    lock: asyncio.Lock,
) -> None:
    line = (
        f"{account.username}:{account.password}:{account.email}:"
        f"{account.ct0}:{account.auth_token}\n"
    )

    def _write_line() -> None:
        locked_path.parent.mkdir(parents=True, exist_ok=True)
        with locked_path.open("a", encoding="utf-8") as handle:
            handle.write(line)

    async with lock:
        await asyncio.to_thread(_write_line)


async def _append_failed_line(
    failed_path: Path,
    account: Account,
    lock: asyncio.Lock,
) -> None:
    line = (
        f"{account.username}:{account.password}:{account.email}:"
        f"{account.ct0}:{account.auth_token}\n"
    )

    def _write_line() -> None:
        failed_path.parent.mkdir(parents=True, exist_ok=True)
        with failed_path.open("a", encoding="utf-8") as handle:
            handle.write(line)

    async with lock:
        await asyncio.to_thread(_write_line)


async def _handle_locked_response(
    body_text: str,
    account: Account,
    locked_path: Path,
    lock: asyncio.Lock,
    worker_name: str,
) -> bool:
    if not _is_account_locked(body_text):
        return False
    _log_step(
        worker_name,
        "locked",
        "skip",
        "written to locked.txt",
        level=logging.WARNING,
    )
    await _append_locked_line(locked_path, account, lock)
    return True


async def _close_session(session: Any) -> None:
    close_fn = getattr(session, "close", None)
    if not callable(close_fn):
        return
    try:
        result = close_fn()
        if inspect.isawaitable(result):
            await result
    except Exception:  # pragma: no cover - oturum kapanamadı
        pass


async def _process_account(
    account: Account,
    config: Config,
    semaphore: asyncio.Semaphore,
    txid_provider: TransactionIdProvider,
    output_path: Path,
    failed_path: Path,
    locked_path: Path,
    output_lock: asyncio.Lock,
    metrics: RunMetrics,
) -> None:
    """Tek bir hesab?? i??leyip API iste??ini g??nder."""

    async with semaphore:
        worker_name = _get_worker_name()
        _log_step(worker_name, "account", "start")
        session = None
        success = False
        locked = False
        try:
            try:
                session = _create_tls_session(async_mode=True)
            except TLSClientConfigError as exc:
                _log_step(
                    worker_name,
                    "session",
                    "fail",
                    f"tls open failed: {exc}",
                    level=logging.ERROR,
                )
                return
            except Exception as exc:  # pragma: no cover - beklenmedik senaryolar
                _log_step(
                    worker_name,
                    "session",
                    "fail",
                    f"tls error: {exc}",
                    level=logging.ERROR,
                )
                return

            try:
                proxy_url = _normalize_proxy(config.proxy_raw)
            except ValueError as exc:
                _log_step(
                    worker_name,
                    "proxy",
                    "fail",
                    str(exc),
                    level=logging.ERROR,
                )
                return

            try:
                _apply_proxy(session, proxy_url)
                _set_auth_cookies(session, account)

                try:
                    transaction_id = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        "/1.1/onboarding/task.json?flow_name=two-factor-auth-app-enrollment",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"init: {exc}",
                        level=logging.ERROR,
                    )
                    return

                components = _build_request_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=transaction_id,
                )
                response = await session.post(
                    components["url"],
                    params=components["params"],
                    headers=components["headers"],
                    json=components["payload"],
                    timeout=config.request_timeout,
                )
                body_text = await _read_response_text(response)
                if await _handle_locked_response(
                    body_text,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return
                flow_token, subtask_id = _extract_flow_data(body_text)
                if not flow_token:
                    _log_step(
                        worker_name,
                        "init",
                        "fail",
                        "flow_token missing",
                        level=logging.WARNING,
                    )
                    return
                if not account.password:
                    _log_step(
                        worker_name,
                        "init",
                        "fail",
                        "password missing",
                        level=logging.ERROR,
                    )
                    return
                if not subtask_id:
                    _log_step(
                        worker_name,
                        "init",
                        "warn",
                        "subtask_id missing; default used",
                        level=logging.WARNING,
                    )
                _log_step(worker_name, "init", "ok")

                try:
                    transaction_id = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        "/1.1/onboarding/task.json",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"password: {exc}",
                        level=logging.ERROR,
                    )
                    return

                password_components = _build_password_subtask_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=transaction_id,
                    flow_token=flow_token,
                    subtask_id=subtask_id,
                )
                response_pw = await session.post(
                    password_components["url"],
                    headers=password_components["headers"],
                    json=password_components["payload"],
                    timeout=config.request_timeout,
                )
                body_text_pw = await _read_response_text(response_pw)
                if await _handle_locked_response(
                    body_text_pw,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return
                flow_token_next = _extract_flow_token(body_text_pw)
                if not flow_token_next:
                    _log_step(
                        worker_name,
                        "password",
                        "fail",
                        "flow_token missing",
                        level=logging.WARNING,
                    )
                    return
                _log_step(worker_name, "password", "ok")

                try:
                    transaction_id = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        "/1.1/onboarding/task.json",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"auth app begin: {exc}",
                        level=logging.ERROR,
                    )
                    return

                auth_app_components = _build_auth_app_begin_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=transaction_id,
                    flow_token=flow_token_next,
                )
                response_app = await session.post(
                    auth_app_components["url"],
                    headers=auth_app_components["headers"],
                    json=auth_app_components["payload"],
                    timeout=config.request_timeout,
                )
                body_text_app = await _read_response_text(response_app)
                if await _handle_locked_response(
                    body_text_app,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return
                flow_token_confirm = _extract_flow_token(body_text_app)
                if not flow_token_confirm:
                    _log_step(
                        worker_name,
                        "auth-app",
                        "fail",
                        "flow_token missing",
                        level=logging.WARNING,
                    )
                    return
                totp_secret = _extract_totp_secret(body_text_app)
                if not totp_secret:
                    _log_step(
                        worker_name,
                        "auth-app",
                        "fail",
                        "totp secret missing",
                        level=logging.WARNING,
                    )
                    return
                try:
                    totp_code = _generate_totp(totp_secret)
                except ValueError as exc:
                    _log_step(
                        worker_name,
                        "totp",
                        "fail",
                        str(exc),
                        level=logging.ERROR,
                    )
                    return
                _log_step(worker_name, "auth-app", "ok")

                try:
                    transaction_id = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        "/1.1/onboarding/task.json",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"auth app confirm: {exc}",
                        level=logging.ERROR,
                    )
                    return

                auth_app_confirm = _build_auth_app_confirm_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=transaction_id,
                    flow_token=flow_token_confirm,
                    totp_code=totp_code,
                )
                response_confirm = await session.post(
                    auth_app_confirm["url"],
                    headers=auth_app_confirm["headers"],
                    json=auth_app_confirm["payload"],
                    timeout=config.request_timeout,
                )
                body_text_confirm = await _read_response_text(response_confirm)
                if await _handle_locked_response(
                    body_text_confirm,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return
                flow_token_complete = _extract_flow_token(body_text_confirm)
                if not flow_token_complete:
                    _log_step(
                        worker_name,
                        "confirm",
                        "fail",
                        "flow_token missing",
                        level=logging.WARNING,
                    )
                    return
                _log_step(worker_name, "confirm", "ok")

                try:
                    transaction_id = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        "/1.1/onboarding/task.json",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"auth app complete: {exc}",
                        level=logging.ERROR,
                    )
                    return

                auth_app_complete = _build_auth_app_complete_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=transaction_id,
                    flow_token=flow_token_complete,
                )
                response_complete = await session.post(
                    auth_app_complete["url"],
                    headers=auth_app_complete["headers"],
                    json=auth_app_complete["payload"],
                    timeout=config.request_timeout,
                )
                body_text_complete = await _read_response_text(response_complete)
                if await _handle_locked_response(
                    body_text_complete,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return
                await _append_output_line(output_path, account, totp_secret, output_lock)
                _log_step(worker_name, "done", "ok", "2FA enabled")
                success = True
            except Exception as exc:  # pragma: no cover - a?? hatalar??
                _log_step(
                    worker_name,
                    "request",
                    "fail",
                    str(exc),
                    level=logging.ERROR,
                )
        finally:
            if session is not None:
                await _close_session(session)
            if success:
                await metrics.add_success()
            else:
                await metrics.add_error()
                if not locked:
                    await _append_failed_line(failed_path, account, output_lock)


async def _run_accounts(
    accounts: List[Account],
    config: Config,
    output_path: Path,
    failed_path: Path,
    locked_path: Path,
) -> RunMetrics:
    semaphore = asyncio.Semaphore(config.threads)
    output_lock = asyncio.Lock()
    metrics = RunMetrics(success=0, error=0, lock=asyncio.Lock())
    # Share provider to avoid re-downloading ondemand.s for every account.
    txid_provider = TransactionIdProvider(_RequestContext(session=None), timeout=config.txid_timeout)
    tasks = [
        asyncio.create_task(
            _process_account(
                account,
                config,
                semaphore,
                txid_provider,
                output_path,
                failed_path,
                locked_path,
                output_lock,
                metrics,
            ),
            name=f"acct:{account.username}",
        )
        for account in accounts
    ]
    for task in tasks:
        try:
            await task
        except Exception as exc:  # pragma: no cover - teorik
            LOGGER.error("Worker task failed unexpectedly: %s", exc)
    return metrics


def main() -> None:
    """Asenkron 2FA kayıt sürecini başlat."""

    base_dir = Path(__file__).resolve().parent
    config = _load_config(base_dir / "config.json")
    output_path = base_dir / "out.txt"
    failed_path = base_dir / "failed.txt"
    locked_path = base_dir / "locked.txt"
    accounts = _parse_accounts(base_dir / "DataUsers.txt")
    if not accounts:
        LOGGER.warning("No accounts found. Exiting.")
        return

    LOGGER.info("%s accounts will be processed with %s threads.", len(accounts), config.threads)
    metrics = asyncio.run(_run_accounts(accounts, config, output_path, failed_path, locked_path))
    LOGGER.info(
        "Run completed. Success: %s, Errors: %s",
        metrics.success,
        metrics.error,
    )


if __name__ == "__main__":
    _configure_logging()
    try:
        main()
    except KeyboardInterrupt:
        LOGGER.warning("User aborted the operation.")
