"""ansel files — classify data files."""

from __future__ import annotations

import sys
import time
from pathlib import Path
from typing import cast

from ..auth import get_token
from ..client import get_json, post_stream
from ..output import format_file_line, on_files_event, print_files_result
from ..parse import JSONObject
from . import resolve_csv_files


def _require_token() -> str | None:
    """Get auth token or print error."""
    token = get_token()
    if not token:
        print(
            'error: no credentials found. Set ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN.',
            file=sys.stderr,
        )
    return token


def _run_list(token: str) -> int:
    """ansel files list"""
    data = get_json(token, '/files')
    if data is None:
        print('error: failed to fetch files', file=sys.stderr)
        return 1

    raw_files = data.get('files', [])
    files: list[JSONObject] = (
        [cast(JSONObject, f) for f in cast(list[object], raw_files) if isinstance(f, dict)]
        if isinstance(raw_files, list)
        else []
    )
    if not files:
        print('no files found')
        return 0

    for f in files:
        print(format_file_line(f))
    return 0


def _run_upload(token: str, path: Path) -> int:
    """ansel files --data <path>"""
    csv_files = resolve_csv_files(path)
    if csv_files is None:
        return 1

    files_data = [('file', csv_file.name, csv_file.read_text()) for csv_file in csv_files]
    start = time.monotonic()
    result = post_stream('/files', token, files=files_data, on_event=on_files_event)
    elapsed = time.monotonic() - start
    return print_files_result(result, elapsed)


def _parse_flags(args: list[str]) -> tuple[list[str], dict[str, str]]:
    """Separate positional args from --flag value pairs."""
    positional: list[str] = []
    flags: dict[str, str] = {}
    i = 0
    while i < len(args):
        if args[i].startswith('--') and i + 1 < len(args):
            flags[args[i][2:]] = args[i + 1]
            i += 2
        else:
            positional.append(args[i])
            i += 1
    return positional, flags


def run(args: list[str]) -> int:
    """Execute the files command."""
    if not args:
        print('files: classify data files')
        print()
        print('  files                    Upload CSVs from current directory')
        print('  files --data <path>      Upload a CSV file or directory')
        print('  files list               List classified files')
        print()
        print('Options:')
        print('  --data PATH       CSV file or directory (default: .)')
        return 1

    positional, flags = _parse_flags(args)

    token = _require_token()
    if not token:
        return 1

    # Subcommands
    if positional and positional[0] == 'list':
        return _run_list(token)

    if positional:
        print(f"error: unknown argument '{positional[0]}'", file=sys.stderr)
        return 1

    # --data flag or default to cwd
    path = Path(flags.get('data', '.'))
    if not path.exists():
        print(f'error: {path} not found', file=sys.stderr)
        return 1
    return _run_upload(token, path)
