import argparse
import csv
import json
import os
from pathlib import Path
from typing import Any, Optional

from tweetapi import (
    AuthenticationError,
    NetworkError,
    RateLimitError,
    TweetAPI,
    TweetAPIError,
)


CSV_FIELDS = [
    "id",
    "username",
    "name",
    "bio",
    "location",
    "website",
    "verified",
    "isBlueVerified",
    "isProtected",
    "followerCount",
    "followingCount",
    "tweetCount",
    "listedCount",
    "createdAt",
]
DANGEROUS_FORMULA_PREFIXES = (
    "=",
    "+",
    "-",
    "@",
    "\t",
    "\r",
    "\n",
    "＝",
    "＋",
    "－",
    "＠",
)


def csv_value(value: Any) -> str:
    """Normalize a value and harden common spreadsheet formula prefixes."""
    if value is None:
        return ""
    if isinstance(value, (dict, list)):
        value = json.dumps(value, ensure_ascii=False, separators=(",", ":"))

    text = str(value).replace("\x00", "")
    if text.startswith(DANGEROUS_FORMULA_PREFIXES):
        return "'" + text
    return text


def read_existing_ids(output_path: Path) -> set[str]:
    """Read only IDs, not full profiles, to deduplicate a resumed export."""
    if not output_path.exists() or output_path.stat().st_size == 0:
        return set()

    with output_path.open("r", encoding="utf-8", newline="") as handle:
        return {
            row["id"]
            for row in csv.DictReader(handle)
            if row.get("id")
        }


def load_checkpoint(checkpoint_path: Path, username: str) -> dict[str, Any]:
    if not checkpoint_path.exists():
        return {"username": username, "pages": 0, "rows": 0}

    state = json.loads(checkpoint_path.read_text(encoding="utf-8"))
    if state.get("username", "").lower() != username.lower():
        raise ValueError(
            f"Checkpoint belongs to @{state.get('username')}, not @{username}"
        )
    return state


def save_checkpoint(checkpoint_path: Path, state: dict[str, Any]) -> None:
    checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
    temporary_path = checkpoint_path.with_name(checkpoint_path.name + ".tmp")
    temporary_path.write_text(
        json.dumps(state, indent=2, sort_keys=True),
        encoding="utf-8",
    )
    temporary_path.replace(checkpoint_path)


def export_followers(
    username: str,
    output_path: Path,
    checkpoint_path: Path,
    max_pages: Optional[int],
) -> None:
    client = TweetAPI(api_key=os.environ["TWEETAPI_KEY"])
    state = load_checkpoint(checkpoint_path, username)

    if state.get("completed"):
        print(f"Export is already complete: {output_path}")
        return

    user_id = state.get("userId")
    if not user_id:
        profile = client.user.get_by_username(username=username)
        user_id = profile["data"]["id"]
        state["userId"] = user_id
        save_checkpoint(checkpoint_path, state)

    output_path.parent.mkdir(parents=True, exist_ok=True)
    seen_ids = read_existing_ids(output_path)
    state["rows"] = len(seen_ids)
    has_header = output_path.exists() and output_path.stat().st_size > 0
    pages_this_run = 0
    cursor = state.get("cursor")

    with output_path.open("a", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS)
        if not has_header:
            writer.writeheader()

        while max_pages is None or pages_this_run < max_pages:
            page = client.user.get_followers(user_id=user_id, cursor=cursor)

            for follower in page.get("data", []):
                follower_id = str(follower.get("id", ""))
                if not follower_id or follower_id in seen_ids:
                    continue

                writer.writerow(
                    {
                        field: csv_value(follower.get(field))
                        for field in CSV_FIELDS
                    }
                )
                seen_ids.add(follower_id)
                state["rows"] = state.get("rows", 0) + 1

            handle.flush()
            pages_this_run += 1
            state["pages"] = state.get("pages", 0) + 1
            cursor = page.get("pagination", {}).get("nextCursor")
            state["cursor"] = cursor
            state["completed"] = not bool(cursor)
            save_checkpoint(checkpoint_path, state)

            print(
                f"pages={state['pages']} rows={state['rows']} "
                f"next_cursor={'yes' if cursor else 'no'}"
            )
            if not cursor:
                break

    if cursor and max_pages is not None:
        print("Stopped at --max-pages. Run the same command to resume.")
    else:
        print(f"Export complete: {output_path}")


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Export Twitter follower profiles to a resumable CSV file."
    )
    parser.add_argument("username", help="Twitter username, with or without @")
    parser.add_argument("--output", default="followers.csv")
    parser.add_argument(
        "--checkpoint",
        help="Defaults to <output>.checkpoint.json",
    )
    parser.add_argument(
        "--max-pages",
        type=int,
        help="Stop after this many pages in the current run",
    )
    args = parser.parse_args()

    username = args.username.lstrip("@").strip()
    if not username:
        parser.error("username cannot be empty")
    if args.max_pages is not None and args.max_pages < 1:
        parser.error("--max-pages must be at least 1")
    if "TWEETAPI_KEY" not in os.environ:
        parser.error("set TWEETAPI_KEY before running the exporter")

    output_path = Path(args.output)
    checkpoint_path = Path(
        args.checkpoint or f"{output_path}.checkpoint.json"
    )

    try:
        export_followers(
            username=username,
            output_path=output_path,
            checkpoint_path=checkpoint_path,
            max_pages=args.max_pages,
        )
    except AuthenticationError:
        raise SystemExit("Authentication failed. Check TWEETAPI_KEY.")
    except RateLimitError as error:
        retry_after = getattr(error, "retry_after", None)
        detail = f" Retry after about {retry_after} seconds." if retry_after else ""
        raise SystemExit("Rate limit reached." + detail)
    except NetworkError:
        raise SystemExit("Network request failed after SDK retries.")
    except (OSError, ValueError) as error:
        raise SystemExit(f"Local export error: {error}")
    except TweetAPIError as error:
        raise SystemExit(
            f"TweetAPI error {error.status_code}: {error.message}"
        )


if __name__ == "__main__":
    main()
