from __future__ import annotations

import logging
import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional

import config_manager
from email_changer import EmailChangeResult, change_email_for_user

LOGGER = logging.getLogger("x_email_changer.main")


@dataclass(slots=True)
class Config:
    threads: int
    proxy: str
    user_agent: str
    request_timeout: float
    mail_service: str
    anymessage_api_key: str
    anymessage_domain: str
    zeus_api_key: str
    zeus_accountcode: str
    zeus_client_secret: str


@dataclass(slots=True)
class Account:
    id: int
    username: str
    password: str
    email: str
    ct0: str
    auth_token: str
    twofa_secret: str
    raw: str


def _configure_logging() -> None:
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(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:
    data = config_manager.load_config()
    threads = int(data.get("threads") or 0)
    if threads < 1:
        raise SystemExit("threads must be >= 1 in config.json.")
    proxy = str(data.get("proxy") or "").strip()
    user_agent = str(data.get("user_agent") or "").strip()
    anymessage_enabled = bool(data.get("mail_service_anymessage"))
    mailtm_enabled = bool(data.get("mail_service_mailtm"))
    zeus_enabled = bool(data.get("mail_service_zeus"))
    enabled_count = sum(int(v) for v in (anymessage_enabled, mailtm_enabled, zeus_enabled))
    if enabled_count > 1:
        raise SystemExit("Only one mail service can be enabled in config.json.")
    if enabled_count == 0:
        legacy = str(data.get("mail_service") or "").strip().lower()
        if legacy in {"mail_tm", "mail-tm"}:
            legacy = "mailtm"
        if legacy in {"anymessage", "mailtm", "zeus"}:
            mail_service = legacy
        else:
            raise SystemExit("Enable a mail service in config.json.")
    else:
        if mailtm_enabled:
            mail_service = "mailtm"
        elif anymessage_enabled:
            mail_service = "anymessage"
        else:
            mail_service = "zeus"
    anymessage_api_key = str(data.get("anymessage_api_key") or "").strip()
    zeus_api_key = str(data.get("zeus_api_key") or "").strip()
    zeus_accountcode = str(data.get("zeus_accountcode") or "HOTMAIL").strip() or "HOTMAIL"
    zeus_client_secret = str(data.get("zeus_client_secret") or "").strip()
    if not proxy or proxy == "YOUR_PROXY_HERE":
        raise SystemExit("proxy is missing in config.json.")
    if not user_agent:
        raise SystemExit("user_agent is missing in config.json.")
    if mail_service == "anymessage" and not anymessage_api_key:
        raise SystemExit("anymessage_api_key is missing in config.json.")
    if mail_service == "zeus" and not zeus_api_key:
        raise SystemExit("zeus_api_key is missing in config.json.")
    return Config(
        threads=threads,
        proxy=proxy,
        user_agent=user_agent,
        request_timeout=float(data.get("request_timeout") or 8.0),
        mail_service=mail_service,
        anymessage_api_key=anymessage_api_key,
        anymessage_domain=str(data.get("anymessage_domain") or "gmail.com").strip() or "gmail.com",
        zeus_api_key=zeus_api_key,
        zeus_accountcode=zeus_accountcode,
        zeus_client_secret=zeus_client_secret,
    )


def _split_account_line(line: str) -> tuple[str, str, str, str, str, str] | None:
    parts = line.split(":")
    if len(parts) == 5:
        return parts[0], parts[1], parts[2], parts[3], parts[4], ""
    if len(parts) == 6:
        return parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]

    if line.count(":") < 4:
        return None

    # Fallback for unexpected extra separators: try to parse from the right.
    try:
        left, ct0, auth_token, twofa = line.rsplit(":", 3)
        left_parts = left.split(":", 2)
        if len(left_parts) == 3:
            return left_parts[0], left_parts[1], left_parts[2], ct0, auth_token, twofa
    except ValueError:
        pass
    try:
        left, ct0, auth_token = line.rsplit(":", 2)
        left_parts = left.split(":", 2)
        if len(left_parts) == 3:
            return left_parts[0], left_parts[1], left_parts[2], ct0, auth_token, ""
    except ValueError:
        pass
    return None


def _parse_accounts(data_path: Path) -> List[Account]:
    if not data_path.exists():
        raise SystemExit(f"DataUsers.txt not found: {data_path}")

    accounts: List[Account] = []
    for line_no, raw_line in enumerate(data_path.read_text(encoding="utf-8-sig").splitlines(), start=1):
        line = raw_line.strip()
        if not line:
            continue
        parsed = _split_account_line(line)
        if not parsed:
            LOGGER.warning("Line skipped (missing ct0/auth_token) [line %s]: %s", line_no, line)
            continue
        username, password, email, ct0, auth_token, twofa = parsed
        account = Account(
            id=line_no,
            username=username.strip(),
            password=password.strip(),
            email=email.strip(),
            ct0=ct0.strip(),
            auth_token=auth_token.strip(),
            twofa_secret=twofa.strip(),
            raw=line,
        )
        accounts.append(account)
    return accounts


def _detect_utf8_encoding(path: Path) -> str:
    """Return utf-8 / utf-8-sig depending on BOM presence so we don't change the file unexpectedly."""
    try:
        with path.open("rb") as handle:
            if handle.read(3).startswith(b"\xef\xbb\xbf"):
                return "utf-8-sig"
    except OSError:
        pass
    return "utf-8"


def _collect_usernames_from_out(out_path: Path) -> set[str]:
    if not out_path.exists():
        return set()
    try:
        content = out_path.read_text(encoding="utf-8", errors="ignore")
    except OSError as exc:
        LOGGER.error("Failed to read out.txt for startup cleanup: %s", exc)
        return set()

    usernames: set[str] = set()
    for raw_line in content.splitlines():
        line = raw_line.strip()
        if not line:
            continue
        # out.txt success format starts with "username:..."
        username = line.split(":", 1)[0].strip()
        if username:
            usernames.add(username)
    return usernames


def _prune_datausers_by_username(data_path: Path, usernames: set[str]) -> int:
    """Remove accounts from DataUsers.txt if their username appears in the given set."""
    if not usernames:
        return 0

    encoding = _detect_utf8_encoding(data_path)
    try:
        original_text = data_path.read_text(encoding=encoding)
    except OSError as exc:
        LOGGER.error("Failed to read DataUsers.txt for startup cleanup: %s", exc)
        return 0

    ends_with_newline = original_text.endswith("\n")
    kept: List[str] = []
    removed = 0
    for raw_line in original_text.splitlines():
        stripped = raw_line.strip()
        if not stripped:
            kept.append(raw_line)
            continue
        if ":" not in stripped:
            kept.append(raw_line)
            continue
        username = stripped.split(":", 1)[0].strip()
        if username and username in usernames:
            removed += 1
            continue
        kept.append(raw_line)

    if removed <= 0:
        return 0

    new_text = "\n".join(kept)
    if ends_with_newline and new_text:
        new_text += "\n"

    tmp_path = data_path.with_suffix(data_path.suffix + ".tmp")
    try:
        tmp_path.write_text(new_text, encoding=encoding)
        tmp_path.replace(data_path)
    except OSError as exc:
        LOGGER.error("Failed to write cleaned DataUsers.txt: %s", exc)
        try:
            if tmp_path.exists():
                tmp_path.unlink()
        except OSError:
            pass
        return 0

    return removed


def _prune_datausers(data_path: Path, processed_lines: Counter[str]) -> int:
    """Remove processed account lines from DataUsers.txt.

    Only exact matches (after .strip()) are removed, and duplicates are handled with counts.
    Returns how many lines were removed.
    """
    if not processed_lines:
        return 0

    to_remove = processed_lines.copy()
    encoding = _detect_utf8_encoding(data_path)
    try:
        original_text = data_path.read_text(encoding=encoding)
    except OSError as exc:
        LOGGER.error("Failed to read DataUsers.txt for pruning: %s", exc)
        return 0

    ends_with_newline = original_text.endswith("\n")
    kept: List[str] = []
    removed = 0
    for raw_line in original_text.splitlines():
        stripped = raw_line.strip()
        if stripped and to_remove.get(stripped, 0) > 0:
            to_remove[stripped] -= 1
            removed += 1
            continue
        kept.append(raw_line)

    if removed <= 0:
        return 0

    new_text = "\n".join(kept)
    if ends_with_newline and new_text:
        new_text += "\n"

    tmp_path = data_path.with_suffix(data_path.suffix + ".tmp")
    try:
        tmp_path.write_text(new_text, encoding=encoding)
        tmp_path.replace(data_path)
    except OSError as exc:
        LOGGER.error("Failed to write pruned DataUsers.txt: %s", exc)
        try:
            if tmp_path.exists():
                tmp_path.unlink()
        except OSError:
            pass
        return 0

    return removed


def _append_line(path: Path, line: str, lock: threading.Lock) -> None:
    with lock:
        path.parent.mkdir(parents=True, exist_ok=True)
        with path.open("a", encoding="utf-8") as handle:
            handle.write(line + "\n")


def _format_success_line(account: Account, result: EmailChangeResult) -> str:
    ct0_value = result.ct0 or account.ct0
    mail_value = (result.email or account.email).strip()
    mail_secret = (result.mail_password or "").strip()
    twofa_value = (account.twofa_secret or "").strip()
    # Output format: id:pass:mail:mailpass:ct0:auth_token:2fa
    return (
        f"{account.username}:{account.password}:{mail_value}:{mail_secret}:"
        f"{ct0_value}:{account.auth_token}:{twofa_value}"
    )


def _format_failure_line(account: Account, reason: str) -> str:
    return f"{account.raw} | {reason}"


def _format_failed_line(account: Account) -> str:
    return account.raw


def _process_account(
    account: Account,
    out_path: Path,
    failed_path: Path,
    locked_path: Path,
    lock: threading.Lock,
    success_counter: Counter[str],
    stop_event: Optional[threading.Event],
) -> str:
    if stop_event and stop_event.is_set():
        return "cancelled"
    result = change_email_for_user(account, stop_event=stop_event)
    if result.error == "cancelled":
        return "cancelled"
    if result.ok and result.email and result.email_id:
        _append_line(out_path, _format_success_line(account, result), lock)
        # Mark this exact input line as processed (used to prune DataUsers.txt at the end).
        with lock:
            success_counter[account.raw] += 1
        return "ok"
    reason = result.error or "failed"
    if result.locked:
        _append_line(locked_path, _format_failure_line(account, reason), lock)
        return "locked"
    _append_line(failed_path, _format_failed_line(account), lock)
    return "failed"


def main() -> None:
    base_dir = Path(__file__).resolve().parent
    cfg = _load_config()
    data_path = base_dir / "DataUsers.txt"
    out_path = base_dir / "out.txt"
    if not data_path.exists():
        raise SystemExit(f"DataUsers.txt not found: {data_path}")

    # Startup cleanup: if out.txt already contains successful accounts from a previous run,
    # remove those usernames from DataUsers.txt so we don't re-process them again.
    existing_usernames = _collect_usernames_from_out(out_path)
    if existing_usernames:
        removed = _prune_datausers_by_username(data_path, existing_usernames)
        if removed:
            LOGGER.info("Startup cleanup: removed %s accounts from DataUsers.txt based on out.txt.", removed)

    accounts = _parse_accounts(data_path)
    if not accounts:
        LOGGER.warning("No accounts found. Exiting.")
        return

    failed_path = base_dir / "failed.txt"
    locked_path = base_dir / "locked.txt"
    lock = threading.Lock()
    success_counter: Counter[str] = Counter()

    LOGGER.info("%s accounts will be processed with %s threads.", len(accounts), cfg.threads)
    counts = {"ok": 0, "failed": 0, "locked": 0, "cancelled": 0}
    stop_event = threading.Event()
    with ThreadPoolExecutor(max_workers=cfg.threads) as executor:
        futures = {
            executor.submit(
                _process_account,
                account,
                out_path,
                failed_path,
                locked_path,
                lock,
                success_counter,
                stop_event,
            ): account
            for account in accounts
        }
        try:
            for future in as_completed(futures):
                account = futures[future]
                try:
                    status = future.result()
                except Exception as exc:
                    status = "failed"
                    LOGGER.error("Account processing exception [line=%s]: %s", account.id, exc)
                    _append_line(failed_path, _format_failed_line(account), lock)
                counts[status] = counts.get(status, 0) + 1
        except KeyboardInterrupt:
            LOGGER.warning("Interrupted by user; cancelling pending tasks.")
            stop_event.set()
            cancelled = 0
            for future in futures:
                if future.cancel():
                    cancelled += 1
            executor.shutdown(wait=False, cancel_futures=True)
            if cancelled:
                counts["cancelled"] = counts.get("cancelled", 0) + cancelled
            removed = _prune_datausers(data_path, success_counter)
            if removed:
                LOGGER.info("DataUsers.txt updated: removed %s processed accounts.", removed)
            LOGGER.info(
                "Stopped. ok=%s failed=%s locked=%s cancelled=%s",
                counts.get("ok", 0),
                counts.get("failed", 0),
                counts.get("locked", 0),
                counts.get("cancelled", 0),
            )
            return

    removed = _prune_datausers(data_path, success_counter)
    if removed:
        LOGGER.info("DataUsers.txt updated: removed %s processed accounts.", removed)

    LOGGER.info(
        "Done. ok=%s failed=%s locked=%s cancelled=%s",
        counts.get("ok", 0),
        counts.get("failed", 0),
        counts.get("locked", 0),
        counts.get("cancelled", 0),
    )


if __name__ == "__main__":
    _configure_logging()
    try:
        main()
    except KeyboardInterrupt:
        LOGGER.warning("Interrupted by user.")
