"""Run the native Alpha003 factor over the observed daily A-share panel."""

from __future__ import annotations

import argparse
import gc
import json
import sys
import time
from pathlib import Path
from typing import Any, Dict, Mapping, Optional, Sequence, Tuple

from backtrader.utils.paths import data_path

SCRIPT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = SCRIPT_DIR / "config.yaml"
EXAMPLE_ID = "027_alpha003_panel_acceptance"
FACTOR_NAME = "alpha003"
FACTOR_MODES = ("native", "build")


def _load_config(path: Path = CONFIG_PATH) -> Dict[str, Any]:
    try:
        import yaml
    except ImportError as exc:
        raise RuntimeError("the example requires PyYAML to read config.yaml") from exc
    with path.open("r", encoding="utf-8") as source:
        value = yaml.safe_load(source)
    if not isinstance(value, dict) or value.get("example_id") != EXAMPLE_ID:
        raise ValueError("config.yaml does not describe %s" % EXAMPLE_ID)
    return value


def _resolve_path(value: str) -> Path:
    path = Path(value).expanduser()
    return path.resolve() if path.is_absolute() else (SCRIPT_DIR / path).resolve()


def _resolve_factor_mode(cli_mode: Optional[str], configured_mode: Optional[str]) -> str:
    mode = cli_mode if cli_mode is not None else configured_mode
    if mode is None:
        mode = "native"
    if mode not in FACTOR_MODES:
        raise ValueError("factor_mode must be 'native' or 'build'")
    return mode


def load_daily_panel(data_config: Mapping[str, Any]) -> Dict[str, Any]:
    """Load the observed daily CSV panel and its shared session grid."""
    import pandas as pd

    directory = data_config.get("directory")
    if not isinstance(directory, str) or not directory:
        raise FileNotFoundError("daily data directory not found: %s" % directory)
    supplied = Path(directory).expanduser()
    root = supplied.resolve() if supplied.is_absolute() else data_path(supplied)
    manifest_path = root / "_metadata" / "manifest.json"
    if not manifest_path.is_file():
        raise FileNotFoundError("daily data directory not found: %s" % root)
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    entries = list(manifest["output"]["symbols"])

    limit = data_config.get("max_symbols", 0)
    if type(limit) is not int or limit < 0:
        raise ValueError("max_symbols must be a non-negative integer")
    if limit and limit < len(entries):
        step = len(entries) / float(limit)
        entries = [entries[int(index * step)] for index in range(limit)]

    calendar = pd.read_csv(root / "_metadata" / "observed_calendar.csv")
    if calendar.empty:
        raise ValueError("observed_calendar.csv is empty")
    timezone_name = data_config["source_timezone"]
    open_times = (
        pd.DatetimeIndex(pd.to_datetime(calendar["first_trade_time"]))
        .tz_localize(timezone_name)
        .tz_convert("UTC")
    )
    close_times = (
        pd.DatetimeIndex(pd.to_datetime(calendar["last_trade_time"]))
        .tz_localize(timezone_name)
        .tz_convert("UTC")
    )
    grid = pd.DataFrame(
        {"open_time": open_times},
        index=pd.DatetimeIndex(close_times, name="close_time"),
    )

    feeds = {}
    assets = []
    for entry in entries:
        frame = pd.read_csv(root / entry["file"], dtype={"trade_date": "string"})
        if frame.empty:
            continue
        symbol = entry["symbol"]
        frame.index = pd.DatetimeIndex(pd.to_datetime(frame["trade_time"]), name="close_time")
        feeds[symbol] = frame.loc[:, ["open", "high", "low", "close", "volume"]].astype("float64")
        assets.append(symbol)
    return {
        "grid": grid,
        "assets": tuple(assets),
        "feeds": feeds,
        "research_start_position": 0,
        "research_end_position": len(grid) - 1,
    }


def _run_factor(
    config: Mapping[str, Any],
    panel: Mapping[str, Any],
    *,
    consume_source_frames: bool = False,
    runonce: bool = False,
) -> Tuple[Any, Any, Any]:
    import backtrader as bt
    from backtrader.brokers import BackBroker
    from backtrader.research import (
        FactorSpec,
        ResearchSpec,
        align_to_grid,
    )
    from backtrader.research.alpha101 import get_alpha
    from backtrader.strategies.factor_strategy import FactorStrategy

    data_config = config["data"]
    grid = panel["grid"]
    first = panel["research_start_position"]
    last = panel["research_end_position"]
    assets = panel["assets"]
    research = ResearchSpec(
        grid=grid,
        start=grid.index[first],
        end=grid.index[last],
        targets=assets,
        source_timezone=data_config["source_timezone"],
        snapshot_id=data_config["snapshot_id"],
        price_basis=data_config["price_basis"],
        calendar_id=data_config["calendar_id"],
        frequency=data_config["frequency"],
        feed_time_kind="close_time",
        groups=dict.fromkeys(assets, data_config["group"]),
    )
    factor_mode = _resolve_factor_mode(None, config.get("factor_mode"))
    indicator = get_alpha(3)
    factor = FactorSpec(
        name=FACTOR_NAME,
        indicator=indicator,
        mode=factor_mode,
        panel_line="factor",
        field_bindings={field: "feed:target:%s" % field for field in indicator.formula_fields},
    )
    cerebro = bt.Cerebro(stdstats=False)

    class CountingBroker(BackBroker):
        def __init__(self):
            super().__init__()
            self.submit_count = 0
            self.cancel_count = 0

        def submit(self, order):
            self.submit_count += 1
            return super().submit(order)

        def cancel(self, order):
            self.cancel_count += 1
            return super().cancel(order)

    broker = CountingBroker()
    cerebro.setbroker(broker)
    source_frames = panel["feeds"]
    if consume_source_frames and type(source_frames) is not dict:
        raise TypeError("exclusive source-frame consumption requires a plain feed dictionary")
    for asset in assets:
        source_frame = source_frames[asset]
        aligned = align_to_grid(
            source_frame,
            research,
            asset,
            data_version=data_config["data_version"],
        )
        cerebro.adddata(aligned.feed, name=asset)
        if consume_source_frames:
            del source_frames[asset]
        del source_frame, aligned
    cerebro.addstrategy(FactorStrategy, research=research, factors={FACTOR_NAME: factor})
    strategies = cerebro.run(runonce=runonce, preload=True)
    if len(strategies) != 1:
        raise RuntimeError("the factor run did not return exactly one strategy")
    strategy = strategies[0]
    spec = strategy._factor_specs_by_name[FACTOR_NAME]
    instances = strategy._factor_instances_by_name[FACTOR_NAME]
    if spec.mode != factor_mode or not instances:
        raise RuntimeError("Alpha003 factor spec did not retain the requested mode")
    if any(instance.factor_mode != factor_mode for instance in instances):
        raise RuntimeError("Alpha003 factor instance selected an unexpected mode")
    return strategy, strategy.get_panel(), indicator


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog=(
            "Exit codes: 0 means factor_values.csv and summary.json were written; "
            "2 means invalid or missing input; 3 means an output I/O failure."
        ),
    )
    parser.add_argument(
        "--output-dir", required=True, help="new output directory; relative to this script"
    )
    parser.add_argument("--data-dir", help="daily data directory; overrides config.yaml")
    parser.add_argument(
        "--max-symbols",
        type=int,
        help="evenly sampled symbol count; 0 uses every symbol in the manifest",
    )
    parser.add_argument(
        "--report", action="store_true", help="write a bilingual HTML factor report"
    )
    parser.add_argument(
        "--report-language", choices=("zh", "en"), default="zh", help="default report language"
    )
    parser.add_argument(
        "--factor-mode",
        choices=FACTOR_MODES,
        default=None,
        help="factor implementation; defaults to config.yaml then native",
    )
    parser.add_argument(
        "--runnext", action="store_true", help="use Cerebro's per-bar engine instead of runonce"
    )
    return parser


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = _parser().parse_args(argv)
    started = time.perf_counter()
    try:
        config = _load_config()
        factor_mode = _resolve_factor_mode(args.factor_mode, config.get("factor_mode"))
        config["factor_mode"] = factor_mode
        if config.get("factor") != FACTOR_NAME or config.get("operator_profile") != "alpha101-v2":
            raise ValueError("this example fixes factor=alpha003 and operator_profile=alpha101-v2")
        if args.data_dir:
            config["data"]["directory"] = str(Path(args.data_dir).expanduser().resolve())
        if args.max_symbols is not None:
            config["data"]["max_symbols"] = args.max_symbols
        output_dir = _resolve_path(args.output_dir)
        output_dir.parent.mkdir(parents=True, exist_ok=True)
        output_dir.mkdir()
    except (ImportError, RuntimeError) as exc:
        print("BLOCKED: %s" % exc, file=sys.stderr)
        return 2
    except OSError as exc:
        print("OUTPUT_ERROR: %s" % exc, file=sys.stderr)
        return 3
    except (TypeError, ValueError) as exc:
        print("INVALID_INPUT: %s" % exc, file=sys.stderr)
        return 2

    try:
        panel = load_daily_panel(config.get("data", {}))
        strategy, collected, indicator = _run_factor(
            config, panel, consume_source_frames=True, runonce=not args.runnext
        )
        factor_instance = strategy.factor_instances[FACTOR_NAME]
        factor_mode = factor_instance.factor_mode
        broker_summary = {
            "submit": strategy.broker.submit_count,
            "cancel": strategy.broker.cancel_count,
        }
        operator_profile = indicator.operator_profile
        indicator_identity = indicator.__module__ + "." + indicator.__qualname__
        symbols = len(collected.target_order)
        dates = len(collected.grid)
        cells = len(collected.factors)
        finite = int(collected.factors[FACTOR_NAME].notna().sum())
        del factor_instance, strategy, panel
        gc.collect()

        factors = collected.factors.reset_index()
        factors.to_csv(output_dir / "factor_values.csv", index=False)
        del factors
        report = None
        if args.report:
            from backtrader.research import write_factor_report

            try:
                report = write_factor_report(
                    collected,
                    FACTOR_NAME,
                    output_dir / ("factor_report_%s.html" % FACTOR_NAME),
                    language=args.report_language,
                    title="027 alpha003 · full-market daily",
                )
                print("REPORT: %s" % report)
            except Exception as exc:
                print("REPORT SKIPPED: %s" % exc, file=sys.stderr)
        summary = {
            "status": "COMPLETED",
            "factor": FACTOR_NAME,
            "factor_mode": factor_mode,
            "factor_calculation": "RAN",
            "operator_profile": operator_profile,
            "indicator": indicator_identity,
            "symbols": symbols,
            "dates": dates,
            "cells": cells,
            "finite": finite,
            "output": "factor_values.csv",
            "broker": broker_summary,
            "report": None if report is None else str(report),
            "elapsed_seconds": round(time.perf_counter() - started, 2),
        }
        (output_dir / "summary.json").write_text(
            json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
            encoding="utf-8",
        )
        print(
            "%s: COMPLETED (%d symbols x %d dates)"
            % (EXAMPLE_ID, summary["symbols"], summary["dates"])
        )
        return 0
    except FileNotFoundError as exc:
        print("BLOCKED: %s" % exc, file=sys.stderr)
        return 2
    except ImportError as exc:
        print("BLOCKED: %s" % exc, file=sys.stderr)
        return 2
    except OSError as exc:
        print("OUTPUT_ERROR: %s" % exc, file=sys.stderr)
        return 3
    except (TypeError, ValueError) as exc:
        print("INVALID_INPUT: %s" % exc, file=sys.stderr)
        return 2
    except Exception as exc:
        print("FAILED: %s: %s" % (type(exc).__name__, exc), file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
