import os
import uuid
from pathlib import Path

import swisseph as swe
from kerykeion import AstrologicalSubjectFactory, ChartDataFactory, ChartDrawer

from chart_utils import extract_transit_wheel


BASE_DIR = Path(__file__).resolve().parent

CHART_DIR = BASE_DIR / "charts" / "transit"
CHART_DIR.mkdir(parents=True, exist_ok=True)

EPHE_PATH = BASE_DIR / "ephe"
swe.set_ephe_path(str(EPHE_PATH))
os.environ["SE_EPHE_PATH"] = str(EPHE_PATH)


def generate_transit_chart_svg(req):
    natal_subject = AstrologicalSubjectFactory.from_birth_data(
        name=req.name,
        year=req.birth_year,
        month=req.birth_month,
        day=req.birth_day,
        hour=req.birth_hour,
        minute=req.birth_minute,
        lng=req.birth_longitude,
        lat=req.birth_latitude,
        tz_str=req.birth_timezone,
        online=False,
    )

    transit_subject = AstrologicalSubjectFactory.from_birth_data(
        name="Transit",
        year=req.transit_year,
        month=req.transit_month,
        day=req.transit_day,
        hour=req.transit_hour,
        minute=req.transit_minute,
        lng=req.transit_longitude,
        lat=req.transit_latitude,
        tz_str=req.transit_timezone,
        online=False,
    )

    chart_data = ChartDataFactory.create_transit_chart_data(
        natal_subject,
        transit_subject,
    )

    file_id = str(uuid.uuid4())[:8]

    full_filename = f"transit_chart_full_{file_id}"
    wheel_filename = f"transit_chart_wheel_{file_id}"

    chart_drawer = ChartDrawer(chart_data=chart_data)

    chart_drawer.save_svg(
        output_path=str(CHART_DIR),
        filename=full_filename,
    )

    full_svg_path = CHART_DIR / f"{full_filename}.svg"
    wheel_svg_path = CHART_DIR / f"{wheel_filename}.svg"

    extracted = extract_transit_wheel(
        str(full_svg_path),
        str(wheel_svg_path),
    )

    if not extracted:
        return {
            "chart_url": f"/charts/transit/{full_filename}.svg",
            "filename": f"{full_filename}.svg",
            "is_wheel_only": False,
        }

    return {
        "chart_url": f"/charts/transit/{wheel_filename}.svg",
        "filename": f"{wheel_filename}.svg",
        "full_chart_url": f"/charts/transit/{full_filename}.svg",
        "is_wheel_only": True,
    }