from __future__ import annotations

import json
from pathlib import Path

from src.ctb_copy.shadow.shadow_models import ShadowCopyDecision, ShadowPortfolioState, ShadowRunSummary


def append_position_decisions(decisions: list[ShadowCopyDecision], path: str | Path) -> Path:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    with target.open("a", encoding="utf-8") as f:
        for decision in decisions:
            f.write(json.dumps(decision.to_json_dict(), sort_keys=True) + "\n")
    return target


def append_shadow_portfolio(state: ShadowPortfolioState, path: str | Path) -> Path:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    with target.open("a", encoding="utf-8") as f:
        f.write(json.dumps(state.to_json_dict(), sort_keys=True) + "\n")
    return target


def write_shadow_result(summary: ShadowRunSummary, path: str | Path) -> Path:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(summary.to_json_dict(), indent=2, sort_keys=True) + "\n", encoding="utf-8")
    return target
