"""ansel forecast — generate demand forecasts."""

from __future__ import annotations

import sys
import time
from pathlib import Path

from ..auth import get_token
from ..client import post_stream
from ..output import print_forecast_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 _parse_flags(args: list[str]) -> tuple[list[str], dict[str, str]]:
    """Separate positional args from --flag value pairs.

    Returns (positional_args, flags_dict).
    """
    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 _build_params(flags: dict[str, str]) -> dict[str, str]:
    """Build query params from parsed flags."""
    params: dict[str, str] = {}
    for key in ('horizon', 'target', 'interval', 'limit'):
        if key in flags:
            params[key] = flags[key]
    return params


def _run_forecast_path(token: str, path: Path, params: dict[str, str]) -> int:
    """ansel forecast <path> — upload CSVs and run full pipeline."""
    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('/forecast', token, files=files_data, params=params)
    elapsed = time.monotonic() - start
    return print_forecast_result(result, elapsed)


def _run_forecast_ids(token: str, file_ids: list[str], params: dict[str, str]) -> int:
    """ansel forecast <file_id...> — run pipeline from pre-uploaded files."""
    start = time.monotonic()
    result = post_stream('/forecast', token, json_body={'file_ids': file_ids}, params=params)
    elapsed = time.monotonic() - start
    return print_forecast_result(result, elapsed)


def run(args: list[str]) -> int:
    """Execute the forecast command."""
    if not args:
        print('ansel forecast: generate demand forecasts')
        print()
        print('Usage:')
        print('  ansel forecast <path>          Full pipeline from local CSV files')
        print('  ansel forecast <file_id...>    Pipeline from pre-uploaded files')
        print()
        print('Flags:')
        print('  --horizon N       Periods to forecast (default: 12)')
        print('  --target STR      What to forecast (default: demand)')
        print('  --interval STR    week | month | quarter (default: month)')
        print('  --limit N         Max series to process (default: 10)')
        print()
        print('Examples:')
        print('  ansel forecast ./sales.csv')
        print('  ansel forecast ./data --horizon 6 --interval week --limit 3')
        print('  ansel forecast fil_abc fil_def --horizon 6')
        return 1

    positional, flags = _parse_flags(args)
    params = _build_params(flags)

    token = _require_token()
    if not token:
        return 1

    # Detect mode: file IDs (fil_ prefix) vs path
    if all(arg.startswith('fil_') for arg in positional):
        return _run_forecast_ids(token, positional, params)

    if len(positional) != 1:
        print('error: provide a single path or one or more file IDs', file=sys.stderr)
        return 1

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

    return _run_forecast_path(token, path, params)
