from __future__ import annotations

from pathlib import Path
from typing import Any
import sys

ST_ROOT = Path(__file__).resolve().parents[1]
if str(ST_ROOT) not in sys.path:
    sys.path.insert(0, str(ST_ROOT))

from Shared.storage.sort_storage import (
    default_database_path,
    get_post_detail,
    get_post_stats,
    initialize_database,
    list_account_posts,
    list_accounts,
    list_deleted_accounts,
    soft_delete_account,
    soft_delete_post,
    upsert_observation,
)


class AnalyzeRepository:
    def __init__(self, st_root: str | Path, db_path: str | Path | None = None) -> None:
        self.st_root = Path(st_root).expanduser().resolve()
        self.db_path = Path(db_path).expanduser().resolve() if db_path else default_database_path(self.st_root)
        initialize_database(self.db_path, self.st_root)

    def health(self) -> dict[str, Any]:
        return {
            "ok": True,
            "service": "Analyze8780",
            "version": "2.3.8.227",
            "db_path": str(self.db_path),
        }

    def accounts(self, *, page: int = 1, page_size: int = 50, include_deleted: bool = False) -> dict[str, Any]:
        return list_accounts(self.db_path, page=page, page_size=page_size, include_deleted=include_deleted)

    def account_posts(self, account_id: int, *, page: int = 1, page_size: int = 50, sort_by: str = "views") -> dict[str, Any]:
        return list_account_posts(
            self.db_path,
            account_id=account_id,
            page=page,
            page_size=page_size,
            sort_by=sort_by,
        )

    def post(self, post_id: int) -> dict[str, Any] | None:
        return get_post_detail(self.db_path, post_id)

    def post_stats(self, post_id: int, *, limit: int = 144) -> list[dict[str, Any]]:
        return get_post_stats(self.db_path, post_id, limit=limit)

    def save_observation(self, payload: dict[str, Any]) -> dict[str, Any]:
        return upsert_observation(
            self.db_path,
            username=str(payload.get("username") or payload.get("account") or ""),
            platform_account_id=str(payload.get("platform_account_id") or ""),
            display_name=str(payload.get("display_name") or ""),
            profile_url=str(payload.get("profile_url") or ""),
            shortcode=str(payload.get("shortcode") or payload.get("code") or ""),
            post_url=str(payload.get("post_url") or ""),
            caption=str(payload.get("caption") or ""),
            published_at=payload.get("published_at"),
            thumbnail_url=str(payload.get("thumbnail_url") or ""),
            video_url=str(payload.get("video_url") or ""),
            views=int(payload.get("views") or payload.get("play_count") or 0),
            likes=int(payload.get("likes") or payload.get("like_count") or 0),
            comments=int(payload.get("comments") or payload.get("comment_count") or 0),
            reposts=int(payload.get("reposts") or payload.get("media_repost_count") or payload.get("share_count") or 0),
            observed_at=payload.get("observed_at") or payload.get("collected_at") or payload.get("captured_at"),
        )

    def delete_account(self, account_id: int) -> dict[str, Any]:
        return soft_delete_account(self.db_path, account_id)

    def delete_post(self, post_id: int) -> dict[str, Any]:
        return soft_delete_post(self.db_path, post_id)

    def deleted_accounts(self) -> list[dict[str, Any]]:
        return list_deleted_accounts(self.db_path)
