"""ansel files — upload and classify data files."""

from __future__ import annotations

import sys
import time
from pathlib import Path
from typing import Any

from ..auth import get_token
from ..client import get_json, post_stream
from ..output import format_file_line, print_files_result


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

    files: list[dict[str, Any]] = data.get('files', [])
    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 <path>"""
    if path.is_dir():
        csv_files = sorted(path.glob('*.csv'))
        if not csv_files:
            print(f'error: no CSV files found in {path}', file=sys.stderr)
            return 1
    elif path.suffix.lower() == '.csv':
        csv_files = [path]
    else:
        print(f'error: {path} is not a CSV file', file=sys.stderr)
        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)
    elapsed = time.monotonic() - start
    return print_files_result(result, elapsed)


def run(args: list[str]) -> int:
    """Execute the files command."""
    if not args:
        print('ansel files: upload and classify CSV data files')
        print()
        print('Usage:')
        print('  ansel files <path>       Upload a CSV file or directory of CSVs')
        print('  ansel files list         List all classified files')
        print()
        print('Each file is classified with: records type, aggregation,')
        print('frequency, and date range.')
        print()
        print('Examples:')
        print('  ansel files ./sales.csv')
        print('  ansel files ./data/')
        print('  ansel files list')
        return 1

    subcommand = args[0]
    token = _require_token()
    if not token:
        return 1

    if subcommand == 'list':
        return _run_list(token)

    path = Path(subcommand)
    if not path.exists():
        print(f'error: {path} not found', file=sys.stderr)
        return 1

    return _run_upload(token, path)
