"""X UserByScreenName isteği için çok iş parçacıklı istemci."""
from __future__ import annotations

import asyncio
import base64
import inspect
import json
import logging
import mimetypes
import os
import random
import re
import string
import threading
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List
from urllib.parse import urlencode

from tid_provider import TransactionIdError, TransactionIdProvider
from tls_client_manager import TLSClient, TLSClientConfigError

LOGGER = logging.getLogger("addedpp.main")
AUTH_TOKEN_PATTERN = re.compile(r"^[0-9a-fA-F]{40}$")
CT0_PATTERN = re.compile(r"^[0-9a-fA-F]{64,}$")
TOTP_PATTERN = re.compile(r"^[A-Z2-7]{8,}$")
MEDIA_DIRNAME = "upload_media"
MEDIA_APPEND_CHUNK_SIZE = 4 * 1024 * 1024
PROFILE_IMAGE_MAX_BYTES = 2 * 1024 * 1024
PROXY_RANDOM_PATTERN = re.compile(r"random", re.IGNORECASE)
PROXY_RANDOM_TOKEN_LENGTH = 12


@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
    totp: str = ""
    mail_password: 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 ParseMetrics:
    parsed: int
    skipped: int
    total_non_empty: int


@dataclass(slots=True)
class MediaAsset:
    path: Path
    total_bytes: int
    media_type: str


@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) -> tuple[List[Account], ParseMetrics]:
    """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] = []
    parse_metrics = ParseMetrics(parsed=0, skipped=0, total_non_empty=0)
    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
        parse_metrics.total_non_empty += 1
        parts = line.split(":")
        if len(parts) < 4:
            LOGGER.warning("Line skipped (format error) [line %s]: %s", line_no, line)
            parse_metrics.skipped += 1
            continue
        username, password, email, *rest = parts
        if not username.strip() or not password.strip() or not email.strip():
            LOGGER.warning("Line skipped (missing username/password/email) [line %s]: %s", line_no, line)
            parse_metrics.skipped += 1
            continue
        filtered = [segment.strip() for segment in rest if segment.strip()]
        mail_password = ""
        if filtered:
            first_rest = filtered[0]
            if (
                not AUTH_TOKEN_PATTERN.fullmatch(first_rest)
                and not CT0_PATTERN.fullmatch(first_rest)
                and not TOTP_PATTERN.fullmatch(first_rest)
            ):
                mail_password = first_rest

        auth_token = next((token for token in reversed(filtered) if AUTH_TOKEN_PATTERN.fullmatch(token)), "")
        ct0 = next((token for token in reversed(filtered) if CT0_PATTERN.fullmatch(token)), "")
        totp = next((token for token in reversed(filtered) if TOTP_PATTERN.fullmatch(token)), "")
        if not auth_token or not ct0:
            if mail_password and len(filtered) == 1:
                LOGGER.warning(
                    "Line skipped (mailpass format; auth_token/ct0 missing) [line %s]: %s",
                    line_no,
                    line,
                )
            else:
                missing_fields: List[str] = []
                if not auth_token:
                    missing_fields.append("auth_token")
                if not ct0:
                    missing_fields.append("ct0")
                LOGGER.warning(
                    "Line skipped (missing %s by regex) [line %s]: %s",
                    " + ".join(missing_fields),
                    line_no,
                    line,
                )
            parse_metrics.skipped += 1
            continue
        account = Account(
            username=username.strip(),
            password=password.strip(),
            email=email.strip(),
            auth_token=auth_token,
            ct0=ct0,
            totp=totp,
            mail_password=mail_password,
        )
        accounts.append(account)
        parse_metrics.parsed += 1
    return accounts, parse_metrics


def _load_media_assets(media_dir: Path) -> List[MediaAsset]:
    """Upload icin kullanilacak dosyalari yukle ve dogrula."""

    if not media_dir.exists():
        raise SystemExit(f"Media klasoru bulunamadi: {media_dir}")
    if not media_dir.is_dir():
        raise SystemExit(f"Media yolu klasor degil: {media_dir}")

    assets: List[MediaAsset] = []
    for path in sorted(media_dir.rglob("*")):
        if not path.is_file():
            continue
        try:
            total_bytes = int(path.stat().st_size)
        except OSError as exc:
            LOGGER.warning("Media file skipped (stat error) [%s]: %s", path.name, exc)
            continue
        if total_bytes <= 0:
            LOGGER.warning("Media file skipped (empty file): %s", path.name)
            continue
        if total_bytes > PROFILE_IMAGE_MAX_BYTES:
            LOGGER.warning(
                "Media file skipped (too large for profile image >2MiB): %s (%s bytes)",
                path,
                total_bytes,
            )
            continue

        media_type, _ = mimetypes.guess_type(str(path))
        if not media_type:
            LOGGER.warning("Media file skipped (unknown media type): %s", path)
            continue
        if not media_type.startswith("image/"):
            LOGGER.warning("Media file skipped (not an image): %s (%s)", path, media_type)
            continue

        assets.append(
            MediaAsset(
                path=path,
                total_bytes=total_bytes,
                media_type=media_type,
            )
        )

    if not assets:
        raise SystemExit(f"Kullanilabilir media dosyasi bulunamadi: {media_dir}")
    return assets


def _build_random_token(length: int = PROXY_RANDOM_TOKEN_LENGTH) -> str:
    alphabet = string.ascii_letters + string.digits
    return "".join(random.choice(alphabet) for _ in range(length))


def _randomize_proxy_placeholder(raw: str) -> str:
    """Proxy string icindeki 'random' placeholder'ini thread bazli token ile degistir."""

    if not raw:
        return raw
    if not PROXY_RANDOM_PATTERN.search(raw):
        return raw
    token = _build_random_token()
    return PROXY_RANDOM_PATTERN.sub(token, raw)


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."""

    cookie_clear = getattr(session.cookies, "clear", None)
    if callable(cookie_clear):
        try:
            cookie_clear()
        except Exception:
            pass
    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,
    screen_name: str,
) -> Dict[str, Any]:
    """UserByScreenName isteği için URL, query, header ve txid path döndür."""

    url = "https://x.com/i/api/graphql/-oaLodhGbbnzJBACb1kk2Q/UserByScreenName"
    variables = {"screen_name": screen_name, "withGrokTranslatedBio": False}
    features = {
        "hidden_profile_subscriptions_enabled": True,
        "profile_label_improvements_pcf_label_in_post_enabled": True,
        "responsive_web_profile_redirect_enabled": False,
        "rweb_tipjar_consumption_enabled": False,
        "verified_phone_label_enabled": False,
        "subscriptions_verification_info_is_identity_verified_enabled": True,
        "subscriptions_verification_info_verified_since_enabled": True,
        "highlights_tweets_tab_ui_enabled": True,
        "responsive_web_twitter_article_notes_tab_enabled": True,
        "subscriptions_feature_can_gift_premium": True,
        "creator_subscriptions_tweet_preview_api_enabled": True,
        "responsive_web_graphql_skip_user_profile_image_extensions_enabled": False,
        "responsive_web_graphql_timeline_navigation_enabled": True,
    }
    field_toggles = {"withPayments": False, "withAuxiliaryUserLabels": True}
    params = {
        "variables": json.dumps(variables, separators=(",", ":"), ensure_ascii=False),
        "features": json.dumps(features, separators=(",", ":"), ensure_ascii=False),
        "fieldToggles": json.dumps(field_toggles, separators=(",", ":"), ensure_ascii=False),
    }
    txid_path = f"/i/api/graphql/-oaLodhGbbnzJBACb1kk2Q/UserByScreenName?{urlencode(params)}"
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "tr,tr-TR;q=0.9,en-US;q=0.8,en;q=0.7",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/json",
            "origin": "https://x.com",
            "priority": "u=1, i",
            "referer": f"https://x.com/{account.username}",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": user_agent,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "X-Twitter-Auth-Type": "OAuth2Session",
            "x-twitter-client-language": "tr",
            "X-Client-Transaction-Id": transaction_id,
        }
    )
    return {"url": url, "params": params, "headers": headers, "txid_path": txid_path}


def _build_media_init_components(
    *,
    account: Account,
    user_agent: str,
    total_bytes: int,
    media_type: str,
) -> Dict[str, Any]:
    """Upload INIT istegi icin URL, query ve header dondur."""

    url = "https://upload.x.com/i/media/upload.json"
    params = {
        "command": "INIT",
        "total_bytes": str(total_bytes),
        "media_type": media_type,
    }
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-language": "tr,tr-TR;q=0.9,en-US;q=0.8,en;q=0.7",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "origin": "https://x.com",
            "priority": "u=1, i",
            "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-auth-type": "OAuth2Session",
            "x-twitter-active-user": "yes",
            "x-twitter-client-language": "tr",
        }
    )
    return {"url": url, "params": params, "headers": headers}


def _build_media_append_components(
    *,
    account: Account,
    user_agent: str,
    media_id: str,
    segment_index: int,
) -> Dict[str, Any]:
    """Upload APPEND istegi icin URL, query ve header dondur."""

    url = "https://upload.x.com/i/media/upload.json"
    params = {
        "command": "APPEND",
        "media_id": media_id,
        "segment_index": str(segment_index),
    }
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-language": "tr,tr-TR;q=0.9,en-US;q=0.8,en;q=0.7",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "origin": "https://x.com",
            "priority": "u=1, i",
            "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-auth-type": "OAuth2Session",
            "x-twitter-active-user": "yes",
            "x-twitter-client-language": "tr",
        }
    )
    return {"url": url, "params": params, "headers": headers}


def _build_media_finalize_components(
    *,
    account: Account,
    user_agent: str,
    media_id: str,
) -> Dict[str, Any]:
    """Upload FINALIZE istegi icin URL, query ve header dondur."""

    url = "https://upload.x.com/i/media/upload.json"
    params = {
        "command": "FINALIZE",
        "media_id": media_id,
    }
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-language": "tr,tr-TR;q=0.9,en-US;q=0.8,en;q=0.7",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "origin": "https://x.com",
            "priority": "u=1, i",
            "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-auth-type": "OAuth2Session",
            "x-twitter-active-user": "yes",
            "x-twitter-client-language": "tr",
        }
    )
    return {"url": url, "params": params, "headers": headers}


def _build_update_profile_image_components(
    *,
    account: Account,
    user_agent: str,
    transaction_id: str,
    media_id: str,
) -> Dict[str, Any]:
    """update_profile_image istegi icin URL, header ve form verisi dondur."""

    url = "https://api.x.com/1.1/account/update_profile_image.json"
    headers = _shuffle_headers(
        {
            "accept": "*/*",
            "accept-language": "tr,tr-TR;q=0.9,en-US;q=0.8,en;q=0.7",
            "authorization": (
                "Bearer "
                "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D"
                "1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
            ),
            "content-type": "application/x-www-form-urlencoded",
            "origin": "https://x.com",
            "priority": "u=1, i",
            "referer": "https://x.com/",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": user_agent,
            "x-client-transaction-id": transaction_id,
            "x-csrf-token": account.ct0,
            "x-twitter-active-user": "yes",
            "x-twitter-auth-type": "OAuth2Session",
            "x-twitter-client-language": "tr",
        }
    )
    data = {
        "include_profile_interstitial_type": "1",
        "include_blocking": "1",
        "include_blocked_by": "1",
        "include_followed_by": "1",
        "include_want_retweets": "1",
        "include_mute_edge": "1",
        "include_can_dm": "1",
        "include_can_media_tag": "1",
        "include_ext_is_blue_verified": "1",
        "include_ext_verified_type": "1",
        "include_ext_profile_image_shape": "1",
        "skip_status": "1",
        "return_user": "true",
        "media_id": media_id,
    }
    return {"url": url, "headers": headers, "data": data}


def _read_media_bytes(path: Path) -> bytes:
    try:
        return path.read_bytes()
    except Exception:
        return b""


def _iter_media_chunks(media_bytes: bytes, chunk_size: int = MEDIA_APPEND_CHUNK_SIZE):
    for index in range(0, len(media_bytes), chunk_size):
        segment_index = index // chunk_size
        yield segment_index, media_bytes[index:index + chunk_size]


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,
    method: str = "POST",
) -> str:
    return provider.generate(method.upper(), 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_user_lookup_result(body_text: str) -> tuple[str, str]:
    if not body_text:
        return "", ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return "", ""
    result = (
        payload.get("data", {})
        .get("user", {})
        .get("result", {})
    )
    if not isinstance(result, dict):
        return "", ""
    rest_id = str(result.get("rest_id") or "").strip()
    core = result.get("core")
    if isinstance(core, dict):
        screen_name = str(core.get("screen_name") or "").strip()
    else:
        screen_name = ""
    return screen_name, rest_id


def _extract_media_id(body_text: str) -> str:
    if not body_text:
        return ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return ""
    media_id = payload.get("media_id_string") or payload.get("media_id")
    return str(media_id or "").strip()


def _extract_processing_state(body_text: str) -> str:
    if not body_text:
        return ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return ""
    processing_info = payload.get("processing_info")
    if not isinstance(processing_info, dict):
        return ""
    state = processing_info.get("state")
    return str(state or "").strip().lower()


def _extract_api_error_message(body_text: str) -> str:
    if not body_text:
        return ""
    try:
        payload = json.loads(body_text)
    except Exception:
        return ""
    errors = payload.get("errors")
    if not isinstance(errors, list):
        return ""
    messages: List[str] = []
    for entry in errors:
        if not isinstance(entry, dict):
            continue
        message = str(entry.get("message") or "").strip()
        if not message:
            continue
        code = entry.get("code")
        if code is None:
            messages.append(message)
        else:
            messages.append(f"{message} (code={code})")
    return " | ".join(messages)


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


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:
    totp_suffix = f":{account.totp}" if account.totp else ""
    line = (
        f"{account.username}:{account.password}:{account.email}:"
        f"{account.ct0}:{account.auth_token}{totp_suffix}\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,
    media_assets: List[MediaAsset],
    failed_path: Path,
    locked_path: Path,
    output_lock: asyncio.Lock,
    metrics: RunMetrics,
) -> None:
    """Tek bir hesabı işleyip UserByScreenName 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:
                randomized_proxy_raw = _randomize_proxy_placeholder(config.proxy_raw)
                proxy_url = _normalize_proxy(randomized_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)

                screen_name = account.username.strip()
                if not screen_name:
                    _log_step(
                        worker_name,
                        "lookup",
                        "fail",
                        "username missing",
                        level=logging.ERROR,
                    )
                    return

                seed_components = _build_request_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id="",
                    screen_name=screen_name,
                )
                try:
                    transaction_id = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        seed_components["txid_path"],
                        "GET",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"lookup: {exc}",
                        level=logging.ERROR,
                    )
                    return

                components = _build_request_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=transaction_id,
                    screen_name=screen_name,
                )
                response = await session.get(
                    components["url"],
                    params=components["params"],
                    headers=components["headers"],
                    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

                status_code = int(getattr(response, "status_code", 0) or 0)
                if status_code >= 400:
                    _log_step(
                        worker_name,
                        "lookup",
                        "fail",
                        f"http {status_code}",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(body_text, 1200),
                    )
                    return

                resolved_screen_name, rest_id = _extract_user_lookup_result(body_text)
                if not rest_id:
                    _log_step(
                        worker_name,
                        "lookup",
                        "fail",
                        "rest_id missing",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(body_text, 1200),
                    )
                    return

                _log_step(
                    worker_name,
                    "lookup",
                    "ok",
                    f"target={resolved_screen_name or screen_name} rest_id={rest_id}",
                )

                selected_asset = random.choice(media_assets)
                media_bytes = await asyncio.to_thread(_read_media_bytes, selected_asset.path)
                if not media_bytes:
                    _log_step(
                        worker_name,
                        "media-read",
                        "fail",
                        f"file unreadable/empty: {selected_asset.path}",
                        level=logging.WARNING,
                    )
                    return

                actual_total_bytes = len(media_bytes)
                if actual_total_bytes != selected_asset.total_bytes:
                    _log_step(
                        worker_name,
                        "media-read",
                        "warn",
                        (
                            f"size changed for {selected_asset.path.name}: "
                            f"{selected_asset.total_bytes} -> {actual_total_bytes}"
                        ),
                        level=logging.WARNING,
                    )
                if actual_total_bytes > PROFILE_IMAGE_MAX_BYTES:
                    _log_step(
                        worker_name,
                        "media-read",
                        "fail",
                        f"file too large for profile image: {actual_total_bytes} bytes (>2MiB)",
                        level=logging.WARNING,
                    )
                    return

                # Defansif: farkli endpoint oncesi auth cookie'lerini tazele.
                _set_auth_cookies(session, account)
                media_components = _build_media_init_components(
                    account=account,
                    user_agent=config.user_agent,
                    total_bytes=actual_total_bytes,
                    media_type=selected_asset.media_type,
                )
                media_response = await session.post(
                    media_components["url"],
                    params=media_components["params"],
                    headers=media_components["headers"],
                    timeout=config.request_timeout,
                )
                media_body_text = await _read_response_text(media_response)
                if await _handle_locked_response(
                    media_body_text,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return

                media_status_code = int(getattr(media_response, "status_code", 0) or 0)
                if media_status_code >= 400:
                    _log_step(
                        worker_name,
                        "media-init",
                        "fail",
                        f"http {media_status_code}",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(media_body_text, 1200),
                    )
                    return

                init_error = _extract_api_error_message(media_body_text)
                if init_error:
                    _log_step(
                        worker_name,
                        "media-init",
                        "fail",
                        init_error,
                        level=logging.WARNING,
                    )
                    return

                media_id = _extract_media_id(media_body_text)
                if not media_id:
                    _log_step(
                        worker_name,
                        "media-init",
                        "fail",
                        "media_id missing",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(media_body_text, 1200),
                    )
                    return

                _log_step(
                    worker_name,
                    "media-init",
                    "ok",
                    (
                        f"file={selected_asset.path.name} bytes={actual_total_bytes} "
                        f"type={selected_asset.media_type} media_id={media_id}"
                    ),
                )

                for segment_index, chunk in _iter_media_chunks(media_bytes):
                    append_components = _build_media_append_components(
                        account=account,
                        user_agent=config.user_agent,
                        media_id=media_id,
                        segment_index=segment_index,
                    )
                    append_response = await session.post(
                        append_components["url"],
                        params=append_components["params"],
                        headers=append_components["headers"],
                        data={"media_data": base64.b64encode(chunk).decode("ascii")},
                        timeout=config.request_timeout,
                    )
                    append_body_text = await _read_response_text(append_response)
                    if await _handle_locked_response(
                        append_body_text,
                        account,
                        locked_path,
                        output_lock,
                        worker_name,
                    ):
                        locked = True
                        return

                    append_status_code = int(getattr(append_response, "status_code", 0) or 0)
                    if append_status_code >= 400:
                        _log_step(
                            worker_name,
                            "media-append",
                            "fail",
                            f"http {append_status_code} seg={segment_index}",
                            level=logging.WARNING,
                        )
                        _log_step(
                            worker_name,
                            "response",
                            "info",
                            _truncate_text(append_body_text, 1200),
                        )
                        return

                    append_error = _extract_api_error_message(append_body_text)
                    if append_error:
                        _log_step(
                            worker_name,
                            "media-append",
                            "fail",
                            f"seg={segment_index} {append_error}",
                            level=logging.WARNING,
                        )
                        _log_step(
                            worker_name,
                            "response",
                            "info",
                            _truncate_text(append_body_text, 1200),
                        )
                        return

                _log_step(
                    worker_name,
                    "media-append",
                    "ok",
                    f"segments={max(1, (actual_total_bytes + MEDIA_APPEND_CHUNK_SIZE - 1) // MEDIA_APPEND_CHUNK_SIZE)}",
                )

                finalize_components = _build_media_finalize_components(
                    account=account,
                    user_agent=config.user_agent,
                    media_id=media_id,
                )
                finalize_response = await session.post(
                    finalize_components["url"],
                    params=finalize_components["params"],
                    headers=finalize_components["headers"],
                    timeout=config.request_timeout,
                )
                finalize_body_text = await _read_response_text(finalize_response)
                if await _handle_locked_response(
                    finalize_body_text,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return

                finalize_status_code = int(getattr(finalize_response, "status_code", 0) or 0)
                if finalize_status_code >= 400:
                    _log_step(
                        worker_name,
                        "media-finalize",
                        "fail",
                        f"http {finalize_status_code}",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(finalize_body_text, 1200),
                    )
                    return

                finalize_error = _extract_api_error_message(finalize_body_text)
                if finalize_error:
                    _log_step(
                        worker_name,
                        "media-finalize",
                        "fail",
                        finalize_error,
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(finalize_body_text, 1200),
                    )
                    return

                finalized_media_id = _extract_media_id(finalize_body_text)
                if not finalized_media_id:
                    _log_step(
                        worker_name,
                        "media-finalize",
                        "fail",
                        "media_id missing",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(finalize_body_text, 1200),
                    )
                    return

                processing_state = _extract_processing_state(finalize_body_text)
                if processing_state in {"pending", "in_progress"}:
                    _log_step(
                        worker_name,
                        "media-finalize",
                        "fail",
                        f"processing_state={processing_state} (STATUS polling not implemented yet)",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(finalize_body_text, 1200),
                    )
                    return

                _log_step(
                    worker_name,
                    "media-finalize",
                    "ok",
                    f"media_id={finalized_media_id}",
                )

                try:
                    profile_txid = await asyncio.to_thread(
                        _generate_transaction_id,
                        txid_provider,
                        "/1.1/account/update_profile_image.json",
                        "POST",
                    )
                except TransactionIdError as exc:
                    _log_step(
                        worker_name,
                        "txid",
                        "fail",
                        f"profile-image: {exc}",
                        level=logging.ERROR,
                    )
                    return

                profile_components = _build_update_profile_image_components(
                    account=account,
                    user_agent=config.user_agent,
                    transaction_id=profile_txid,
                    media_id=finalized_media_id,
                )
                profile_response = await session.post(
                    profile_components["url"],
                    headers=profile_components["headers"],
                    data=profile_components["data"],
                    timeout=config.request_timeout,
                )
                profile_body_text = await _read_response_text(profile_response)
                if await _handle_locked_response(
                    profile_body_text,
                    account,
                    locked_path,
                    output_lock,
                    worker_name,
                ):
                    locked = True
                    return

                profile_status_code = int(getattr(profile_response, "status_code", 0) or 0)
                if profile_status_code >= 400:
                    _log_step(
                        worker_name,
                        "profile-image",
                        "fail",
                        f"http {profile_status_code}",
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(profile_body_text, 1200),
                    )
                    return

                profile_error = _extract_api_error_message(profile_body_text)
                if profile_error:
                    _log_step(
                        worker_name,
                        "profile-image",
                        "fail",
                        profile_error,
                        level=logging.WARNING,
                    )
                    _log_step(
                        worker_name,
                        "response",
                        "info",
                        _truncate_text(profile_body_text, 1200),
                    )
                    return

                _log_step(
                    worker_name,
                    "profile-image",
                    "ok",
                    f"media_id={finalized_media_id}",
                )
                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,
    media_assets: List[MediaAsset],
    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,
                media_assets,
                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 UserByScreenName istek s?recini ba?lat."""

    base_dir = Path(__file__).resolve().parent
    config = _load_config(base_dir / "config.json")
    failed_path = base_dir / "failed.txt"
    locked_path = base_dir / "locked.txt"
    media_dir = base_dir / MEDIA_DIRNAME
    accounts, parse_metrics = _parse_accounts(base_dir / "DataUsers.txt")
    LOGGER.info(
        "Parse summary. Parsed: %s | Skipped: %s | Total non-empty: %s",
        parse_metrics.parsed,
        parse_metrics.skipped,
        parse_metrics.total_non_empty,
    )
    if not accounts:
        LOGGER.warning("No accounts found. Exiting.")
        return

    media_assets = _load_media_assets(media_dir)
    LOGGER.info(
        "%s eligible media file loaded from %s (max size: %s bytes)",
        len(media_assets),
        media_dir,
        PROFILE_IMAGE_MAX_BYTES,
    )
    LOGGER.info("%s accounts will be processed with %s threads.", len(accounts), config.threads)
    metrics = asyncio.run(_run_accounts(accounts, config, media_assets, 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.")
