"""Teach-and-repeat visual mapping primitives.

This is intentionally a pragmatic competition prototype rather than a claim of
metric monocular SLAM.  It combines ORB frame registration, recorded vehicle
inputs, a topological keyframe graph and a projected obstacle layer.  The result
is stable enough to visualize mapping and to repeat a demonstrated route while
remaining honest about the source of scale.
"""

from __future__ import annotations

import heapq
import json
import math
from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Optional

import cv2
import numpy as np
from PIL import Image


SESSIONS_DIR = Path(__file__).resolve().parent / "sessions"
LATEST_FILE = SESSIONS_DIR / "latest.json"


@dataclass
class FeatureSet:
    points: np.ndarray
    descriptors: Optional[np.ndarray]


@dataclass
class VisualMotion:
    matches: int = 0
    inliers: int = 0
    score: float = 0.0
    tx: float = 0.0
    ty: float = 0.0
    rotation: float = 0.0
    scale: float = 1.0
    flow: float = 0.0
    current_points: Optional[np.ndarray] = None


@dataclass
class Pose2D:
    x: float = 0.0
    y: float = 0.0
    theta: float = 0.0


@dataclass
class DetectedObstacle:
    bbox: tuple[int, int, int, int]
    center: tuple[float, float]
    area: float


@dataclass
class KeyframeRecord:
    id: int
    timestamp: float
    phase: str
    pose: tuple[float, float, float]
    keys: dict[str, bool]
    frame: str
    features: str
    feature_count: int


def pil_to_bgr(image: Image.Image, processing_width: int = 960) -> np.ndarray:
    rgb = np.asarray(image.convert("RGB"))
    bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
    if processing_width and bgr.shape[1] != processing_width:
        height = round(bgr.shape[0] * processing_width / bgr.shape[1])
        bgr = cv2.resize(bgr, (processing_width, height), interpolation=cv2.INTER_AREA)
    return bgr


class FeatureEngine:
    def __init__(self, maximum_features: int = 1400) -> None:
        self.orb = cv2.ORB_create(
            nfeatures=maximum_features,
            scaleFactor=1.2,
            nlevels=8,
            edgeThreshold=18,
            fastThreshold=12,
        )
        self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)

    @staticmethod
    def mask_for(gray: np.ndarray) -> np.ndarray:
        height, width = gray.shape
        mask = np.zeros_like(gray, dtype=np.uint8)
        mask[int(height * 0.08) : int(height * 0.80), :] = 255
        # Exclude the rover and typical gauge region in chase-camera footage.
        cv2.rectangle(
            mask,
            (int(width * 0.34), int(height * 0.58)),
            (int(width * 0.66), height),
            0,
            -1,
        )
        cv2.rectangle(
            mask,
            (int(width * 0.73), int(height * 0.50)),
            (width, height),
            0,
            -1,
        )
        return mask

    def extract(self, frame: np.ndarray) -> FeatureSet:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        keypoints, descriptors = self.orb.detectAndCompute(gray, self.mask_for(gray))
        points = (
            np.array([point.pt for point in keypoints], dtype=np.float32)
            if keypoints
            else np.empty((0, 2), dtype=np.float32)
        )
        return FeatureSet(points=points, descriptors=descriptors)

    def compare(self, first: FeatureSet, second: FeatureSet) -> VisualMotion:
        if (
            first.descriptors is None
            or second.descriptors is None
            or len(first.descriptors) < 8
            or len(second.descriptors) < 8
        ):
            return VisualMotion()
        pairs = self.matcher.knnMatch(first.descriptors, second.descriptors, k=2)
        good = [pair[0] for pair in pairs if len(pair) == 2 and pair[0].distance < 0.75 * pair[1].distance]
        if len(good) < 6:
            return VisualMotion(matches=len(good))
        source = np.float32([first.points[item.queryIdx] for item in good])
        target = np.float32([second.points[item.trainIdx] for item in good])
        matrix, inlier_mask = cv2.estimateAffinePartial2D(
            source,
            target,
            method=cv2.RANSAC,
            ransacReprojThreshold=3.5,
            maxIters=1200,
            confidence=0.995,
        )
        deltas = target - source
        flow = float(np.median(np.linalg.norm(deltas, axis=1)))
        if matrix is None:
            return VisualMotion(
                matches=len(good),
                flow=flow,
                current_points=target,
            )
        inliers = int(inlier_mask.sum()) if inlier_mask is not None else 0
        scale = float(math.hypot(matrix[0, 0], matrix[1, 0]))
        rotation = float(math.atan2(matrix[1, 0], matrix[0, 0]))
        denominator = max(1, min(len(first.points), len(second.points)))
        return VisualMotion(
            matches=len(good),
            inliers=inliers,
            score=inliers / denominator,
            tx=float(matrix[0, 2]),
            ty=float(matrix[1, 2]),
            rotation=rotation,
            scale=scale,
            flow=flow,
            current_points=target[inlier_mask.ravel().astype(bool)]
            if inlier_mask is not None
            else target,
        )


class PoseTracker:
    def __init__(self) -> None:
        self.pose = Pose2D()

    def reset(self, pose: Optional[Pose2D] = None) -> None:
        self.pose = pose or Pose2D()

    def update(
        self,
        motion: VisualMotion,
        keys: dict[str, bool],
        dt: float,
    ) -> Pose2D:
        dt = min(max(dt, 0.0), 0.35)
        turn = float(keys.get("left", False)) - float(keys.get("right", False))
        direction = float(keys.get("up", False)) - float(keys.get("down", False))
        visual_turn = max(-0.12, min(0.12, -motion.rotation))
        self.pose.theta += turn * 0.92 * dt + visual_turn * 0.22
        self.pose.theta = math.atan2(math.sin(self.pose.theta), math.cos(self.pose.theta))

        if direction:
            visual_gain = 1.0 + min(1.5, motion.flow / 18.0)
            distance = direction * 3.8 * visual_gain * dt
            self.pose.x += math.cos(self.pose.theta) * distance
            self.pose.y += math.sin(self.pose.theta) * distance
        return Pose2D(self.pose.x, self.pose.y, self.pose.theta)


def detect_obstacles(frame: np.ndarray) -> tuple[list[DetectedObstacle], np.ndarray]:
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    height, width = gray.shape
    dark = cv2.inRange(gray, 0, 52)
    roi = np.zeros_like(dark)
    horizon, bottom = int(height * 0.25), int(height * 0.79)
    roi[horizon:bottom, :] = 255
    cv2.rectangle(
        roi,
        (int(width * 0.34), int(height * 0.55)),
        (int(width * 0.66), bottom),
        0,
        -1,
    )
    dark = cv2.bitwise_and(dark, roi)
    kernel = np.ones((3, 3), np.uint8)
    dark = cv2.morphologyEx(dark, cv2.MORPH_OPEN, kernel)
    dark = cv2.morphologyEx(dark, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
    contours, _ = cv2.findContours(dark, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    obstacles: list[DetectedObstacle] = []
    for contour in contours:
        area = float(cv2.contourArea(contour))
        if not 35.0 <= area <= 11000.0:
            continue
        x, y, box_w, box_h = cv2.boundingRect(contour)
        if box_w < 4 or box_h < 3:
            continue
        obstacles.append(
            DetectedObstacle(
                bbox=(x, y, x + box_w, y + box_h),
                center=(x + box_w / 2.0, y + box_h / 2.0),
                area=area,
            )
        )
    return obstacles, dark


class OccupancyAccumulator:
    def __init__(self, resolution: float = 1.0) -> None:
        self.resolution = resolution
        self.hits: dict[tuple[int, int], int] = {}

    def add(self, pose: Pose2D, obstacles: list[DetectedObstacle], frame_shape: tuple[int, ...]) -> None:
        height, width = frame_shape[:2]
        horizon, bottom = height * 0.25, height * 0.79
        span = max(1.0, bottom - horizon)
        for obstacle in obstacles:
            u, v = obstacle.center
            if not horizon <= v <= bottom:
                continue
            depth_ratio = max(0.0, min(1.0, (bottom - v) / span))
            forward = 2.0 + 30.0 * depth_ratio**1.65
            lateral = ((u - width / 2.0) / (width / 2.0)) * forward * 0.82
            world_x = (
                pose.x
                + math.cos(pose.theta) * forward
                - math.sin(pose.theta) * lateral
            )
            world_y = (
                pose.y
                + math.sin(pose.theta) * forward
                + math.cos(pose.theta) * lateral
            )
            cell = (
                round(world_x / self.resolution),
                round(world_y / self.resolution),
            )
            self.hits[cell] = min(255, self.hits.get(cell, 0) + 1)

    def stable_points(self, minimum_hits: int = 2) -> list[tuple[float, float, int]]:
        return [
            (cell[0] * self.resolution, cell[1] * self.resolution, hits)
            for cell, hits in self.hits.items()
            if hits >= minimum_hits
        ]

    def serialise(self) -> list[list[float]]:
        return [
            [cell[0], cell[1], hits]
            for cell, hits in sorted(self.hits.items())
        ]

    @classmethod
    def from_serialised(
        cls, values: list[list[float]], resolution: float = 1.0
    ) -> "OccupancyAccumulator":
        result = cls(resolution)
        result.hits = {(int(x), int(y)): int(hits) for x, y, hits in values}
        return result


def _write_jpeg(path: Path, frame: np.ndarray) -> None:
    ok, encoded = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 88])
    if not ok:
        raise RuntimeError(f"Could not encode keyframe: {path}")
    encoded.tofile(str(path))


def _read_jpeg(path: Path) -> np.ndarray:
    data = np.fromfile(str(path), dtype=np.uint8)
    image = cv2.imdecode(data, cv2.IMREAD_COLOR)
    if image is None:
        raise RuntimeError(f"Could not read keyframe: {path}")
    return image


class SessionRecorder:
    def __init__(self, occupancy: OccupancyAccumulator) -> None:
        SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
        stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.directory = SESSIONS_DIR / stamp
        suffix = 1
        while self.directory.exists():
            self.directory = SESSIONS_DIR / f"{stamp}_{suffix}"
            suffix += 1
        (self.directory / "frames").mkdir(parents=True)
        (self.directory / "features").mkdir(parents=True)
        self.occupancy = occupancy
        self.keyframes: list[KeyframeRecord] = []
        self.b_index: Optional[int] = None
        self.started_at = datetime.now().isoformat(timespec="seconds")

    def add_keyframe(
        self,
        timestamp: float,
        phase: str,
        pose: Pose2D,
        keys: dict[str, bool],
        frame: np.ndarray,
        features: FeatureSet,
    ) -> int:
        index = len(self.keyframes)
        frame_rel = Path("frames") / f"{index:05d}.jpg"
        feature_rel = Path("features") / f"{index:05d}.npz"
        _write_jpeg(self.directory / frame_rel, frame)
        np.savez_compressed(
            self.directory / feature_rel,
            points=features.points,
            descriptors=features.descriptors
            if features.descriptors is not None
            else np.empty((0, 32), dtype=np.uint8),
        )
        self.keyframes.append(
            KeyframeRecord(
                id=index,
                timestamp=timestamp,
                phase=phase,
                pose=(pose.x, pose.y, pose.theta),
                keys=dict(keys),
                frame=str(frame_rel).replace("\\", "/"),
                features=str(feature_rel).replace("\\", "/"),
                feature_count=len(features.points),
            )
        )
        return index

    def mark_b(self) -> None:
        if not self.keyframes:
            raise RuntimeError("还没有关键帧，无法标记B点")
        self.b_index = len(self.keyframes) - 1

    def finish(self) -> Path:
        if len(self.keyframes) < 4:
            raise RuntimeError("有效关键帧太少，请先完成一次人工驾驶")
        if self.b_index is None:
            raise RuntimeError("尚未标记B点，请在到达B时按F6")
        metadata = {
            "version": 1,
            "created_at": self.started_at,
            "finished_at": datetime.now().isoformat(timespec="seconds"),
            "b_index": self.b_index,
            "keyframes": [asdict(item) for item in self.keyframes],
            "occupancy_resolution": self.occupancy.resolution,
            "occupancy": self.occupancy.serialise(),
        }
        metadata_path = self.directory / "map.json"
        metadata_path.write_text(
            json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8"
        )
        LATEST_FILE.write_text(
            json.dumps({"session": str(self.directory)}, ensure_ascii=False),
            encoding="utf-8",
        )
        return metadata_path


@dataclass
class LoadedKeyframe:
    record: KeyframeRecord
    features: FeatureSet


@dataclass
class LoadedSession:
    directory: Path
    keyframes: list[LoadedKeyframe]
    b_index: int
    occupancy: OccupancyAccumulator

    @classmethod
    def latest(cls) -> "LoadedSession":
        if not LATEST_FILE.exists():
            raise RuntimeError("没有已保存的示教地图，请先完成一次人工建图")
        pointer = json.loads(LATEST_FILE.read_text(encoding="utf-8"))
        return cls.load(Path(pointer["session"]))

    @classmethod
    def load(cls, directory: Path) -> "LoadedSession":
        metadata = json.loads((directory / "map.json").read_text(encoding="utf-8"))
        keyframes: list[LoadedKeyframe] = []
        for item in metadata["keyframes"]:
            record = KeyframeRecord(**item)
            arrays = np.load(directory / record.features)
            descriptors = arrays["descriptors"]
            keyframes.append(
                LoadedKeyframe(
                    record=record,
                    features=FeatureSet(
                        points=arrays["points"].astype(np.float32),
                        descriptors=descriptors.astype(np.uint8)
                        if descriptors.size
                        else None,
                    ),
                )
            )
        occupancy = OccupancyAccumulator.from_serialised(
            metadata.get("occupancy", []),
            float(metadata.get("occupancy_resolution", 1.0)),
        )
        return cls(
            directory=directory,
            keyframes=keyframes,
            b_index=int(metadata["b_index"]),
            occupancy=occupancy,
        )


def _pose_distance(first: KeyframeRecord, second: KeyframeRecord) -> float:
    return math.hypot(first.pose[0] - second.pose[0], first.pose[1] - second.pose[1])


def _astar_graph(
    records: list[KeyframeRecord],
    start: int,
    goal: int,
    allowed: set[int],
) -> list[int]:
    adjacency: dict[int, list[tuple[int, float]]] = {index: [] for index in allowed}
    for index in range(len(records) - 1):
        if index in allowed and index + 1 in allowed:
            weight = max(0.1, _pose_distance(records[index], records[index + 1]))
            adjacency[index].append((index + 1, weight))
            adjacency[index + 1].append((index, weight))
    queue: list[tuple[float, float, int]] = [(0.0, 0.0, start)]
    best = {start: 0.0}
    previous: dict[int, int] = {}
    while queue:
        _, cost, node = heapq.heappop(queue)
        if node == goal:
            route = [node]
            while node in previous:
                node = previous[node]
                route.append(node)
            return list(reversed(route))
        if cost > best.get(node, float("inf")):
            continue
        for neighbor, weight in adjacency.get(node, []):
            candidate = cost + weight
            if candidate >= best.get(neighbor, float("inf")):
                continue
            best[neighbor] = candidate
            previous[neighbor] = node
            heuristic = _pose_distance(records[neighbor], records[goal])
            heapq.heappush(queue, (candidate + heuristic, candidate, neighbor))
    return []


def topological_routes(session: LoadedSession) -> tuple[list[int], list[int]]:
    records = [item.record for item in session.keyframes]
    outbound_allowed = set(range(0, session.b_index + 1))
    return_allowed = set(range(session.b_index, len(records)))
    outbound = _astar_graph(records, 0, session.b_index, outbound_allowed)
    return_route = _astar_graph(
        records, session.b_index, len(records) - 1, return_allowed
    )
    if not outbound or not return_route:
        raise RuntimeError("拓扑图中没有完整的A→B→A路线")
    return outbound, return_route


def keyframe_image(session: LoadedSession, index: int) -> np.ndarray:
    return _read_jpeg(session.directory / session.keyframes[index].record.frame)
