from __future__ import annotations

import hashlib


MANAGED_MARKER = "This README is managed by LiveryLab."


def _managed(text: str) -> str:
    return text.replace("\r\n", "\n").strip() + f"\n\n{MANAGED_MARKER}\n"


def render_release_readme(template: str, version: str, generated_at: str, portable_zip_name: str) -> str:
    version_label = str(version or "0.0.0").strip()
    if version_label.lower().startswith("v"):
        version_label = version_label[1:]
    zip_name = str(portable_zip_name or "").strip()
    folder_name = zip_name[:-4] if zip_name.lower().endswith(".zip") else zip_name
    return str(template).format(
        version=version_label or "0.0.0",
        generated_at=str(generated_at or "").strip(),
        portable_zip_name=zip_name,
        portable_folder_name=folder_name,
    )


LIVERY_PACKAGE_EXPORT_README = _managed("""LiveryLab shared package export folder

This folder stores portable exports shared across LiveryLab workflows. It can
contain Advanced livery packages, Skin Packs, Workspace Transfer bundles,
Driver Profile packages, Tyre Brand packages, Numberplate template packages,
and Custom Grid presets.

Individual Official livery packages are exported to
OfficialLiveryPackageExport instead. Editable work never belongs in either
export folder:
- Advanced project files belong in LiveryProjects.
- Official project files belong in OfficialLiveryProjects.

Imported packages are added to LiveryLab locally first. They are not activated
in AC EVO until you explicitly use Activate in Game. Use Workspace Transfer
when you need to move complete editable projects to another installation.

Do not edit package manifests manually unless you are intentionally repairing
an export.
""")


ADVANCED_PROJECTS_README = _managed("""LiveryLab Advanced project workspace

This folder contains editable projects for the Advanced workflow. Advanced
liveries use extracted AC EVO content, are intended for Single Player, and are
shown through the Vehicle Hub after activation.

Keep exported PNG textures and optional editor source files here. The exported
PNG files are the source used by LiveryLab for the 3D Livery Preview, package
export, Activate in Game, and Update in Game. Saving a PSD, PSB, Affinity,
GIMP, Krita, SVG, or other editor file alone does not update the livery.

Advanced activation writes the prepared livery into the AC EVO game content
structure only after an explicit confirmation. A complete game content extract
is required for this workflow. Advanced liveries are not multiplayer-safe.

Official projects use OfficialLiveryProjects instead. Finished portable ZIP
exports belong in LiveryPackageExport.
""")


ADVANCED_LIBRARY_README = _managed("""LiveryLab Advanced livery library

This folder stores local, ready-to-activate data for the Advanced workflow. It
contains Advanced My Liveries entries plus reusable Driver Profiles, Tyre
Brands, Numberplate templates, Custom Grid presets, metadata, and converted
tool outputs.

Files stay local until you explicitly use Activate in Game, Update in Game, or
another confirmed game-write action. Advanced activation writes into the AC
EVO game content structure and is intended for Single Player.

Editable Advanced source files belong in LiveryProjects. Official projects and
Official read-only packages are stored separately in OfficialLiveryProjects
and OfficialLiveryLibrary.
""")


ADVANCED_CONVERTED_README = _managed("""LiveryLab Advanced converted files

This folder stores generated outputs from LiveryLab conversion and inspection
tools used by the Advanced workflow. It keeps texture, mesh, UV, and material
report outputs away from the AC EVO game folders by default.

Common subfolders:
- Textures: PNG, DDS, texturemips, and material texture exports.
- Meshes: exported OBJ data and mesh inspection outputs.
- UV: generated UV layouts for livery editing.

Treat this folder as disposable tool output. Keep editable Advanced artwork in
LiveryProjects and ready-to-activate data in LiveryLibrary/LocalSkins.
""")


OFFICIAL_PROJECTS_README = _managed("""LiveryLab Official project workspace

This folder contains editable projects for the Official workflow. Each livery
has its own car and project folder. That project folder is the source of truth
for its PNG textures, Live 3D Preview, thumbnail, metadata, and required
SavedCar data.

Official projects do not require a complete AC EVO content extract. Activation
writes to Saved Games/ACE/ExternalLiveries instead of the extracted game
content structure. Activated liveries are found in AC EVO under
Vehicles -> My Cars, not in the Vehicle Hub.

Official liveries can work in Multiplayer when every participant who needs to
see the design has the same livery installed. AC EVO currently does not display
the custom LiveryLab livery name in game.

Do not move project files to LiveryProjects; that folder belongs to the
Advanced workflow. Finished Official packages belong in
OfficialLiveryPackageExport.
""")


OFFICIAL_LIBRARY_README = _managed("""LiveryLab Official livery library

This folder contains LiveryLab-managed data for the Official workflow. It can
include imported read-only Official liveries, prepared preview resources,
SavedCar templates, local package data, and the Official livery trash.

Do not edit files here as a normal livery workflow. Editable Official projects
belong in OfficialLiveryProjects. Read-only package content remains read-only
after import.

Importing or restoring an Official livery only adds it to My Liveries locally.
It remains inactive until you explicitly use Activate in Game. Activation
writes to Saved Games/ACE/ExternalLiveries; it does not require a complete game
content extract.
""")


OFFICIAL_PACKAGE_EXPORT_README = _managed("""LiveryLab Official package export folder

This folder stores portable single-livery packages exported from the Official
workflow. Official packages can be exported as read-only sharing packages or,
when supported, as editable project packages.

Importing a package adds it to Official My Liveries locally and does not
activate it in AC EVO. Read-only packages stay locked. Editable packages restore
their Official project workspace.

Use LiveryPackageExport for Skin Packs, Workspace Transfer bundles, Advanced
packages, and the other shared LiveryLab export types. Do not edit package
manifests manually.
""")


ONLINE_LEAGUE_PROJECTS_README = _managed("""LiveryLab Online League projects

This folder stores local Online League pack projects. Projects are separated
from installed packs and finished exports. Online League supports the Official
ExternalLiveries workflow only.

Projects are organizer-side drafts. Imported livery sources are reduced to
ExternalLiveries payloads and do not retain or export Garage SavedCars.
""")


ONLINE_LEAGUE_LIBRARY_README = _managed("""LiveryLab Online League library

This folder stores imported Official Online League packs separately from My
Liveries and organizer projects.

Imported packs contain ExternalLiveries payloads only. Importing a pack does
not activate it in AC EVO automatically. Activate and deactivate imported packs
from the Online League area. League-owned files are preserved in this folder's
DeploymentBackups area when their last active pack is deactivated.
""")


ONLINE_LEAGUE_PACKAGE_EXPORT_README = _managed("""LiveryLab Online League package exports

This folder stores distributable Official Online League ZIPs for organizers
and end users. League exports contain ExternalLiveries payloads without Garage
SavedCars.

Import these ZIPs through the Online League area. Importing a pack does not
activate its liveries in AC EVO automatically.
""")


DRIVER_PROJECT_README = """LiveryLab Advanced driver project

This folder contains the editable source files for one local Driver Profile in
the Advanced workflow. Driver Profiles are not part of the Official workflow.

LiveryLab syncs these project files into the Driver Profile stored in
LiveryLibrary. The profile is written into Assetto Corsa EVO only when you
activate or update an Advanced livery that uses it.

Common files:
- driver_project.json: LiveryLab project manifest. Do not edit this manually
  unless you are intentionally repairing a project.
- helmet.png, suit.png, gloves.png, visor.png: editable PNG texture sources.
  Edit these files, then use LiveryLab to sync/update the driver profile.
- preview.png: local preview image used by LiveryLab.
- *_uv.png: UV helper images for painting and alignment. These files do not
  affect the driver directly and are not synced as active driver textures.

Keep optional editor source files such as PSD, PSB, XCF, KRA, or Affinity files
here. The PNG files listed in driver_project.json are the source of truth for
the LiveryLab driver workflow.
"""


def advanced_project_readme(car_model: str, skin_id: str, display_name: str, plate_filename: str = "plate_r.png") -> str:
    return f"""LiveryLab Advanced Skin Project
================================

This folder is the editable source of truth for one Advanced workflow livery.

Skin:
- Car: {car_model or '-'}
- Skin ID: {skin_id or '-'}
- Display name: {display_name or '-'}

Workflow:
- Advanced liveries require a complete AC EVO content extract.
- They are intended for Single Player and are not multiplayer-safe.
- After activation, use the Vehicle Hub to select the livery.
- Activate in Game and Update in Game write the prepared project state into the
  AC EVO game content structure after explicit confirmation.

Important:
- Exported PNG texture files in this folder drive preview, package export, and
  game updates. Editing an editor source file alone does not update LiveryLab.
- ext_skin_c.png is the main visible body texture.
- Save changed PNGs back into this folder, then use 3D Livery Preview to inspect
  them before activating or updating the livery.

Optional editor source files:
PSD, PSB, Affinity, GIMP, Krita, SVG, and similar files can stay here for your
own editing workflow. They are not synchronized into the game directly.

Main livery files
-----------------
ext_skin_c.png
Main body color texture and the most important exported PNG.

EXT_SKIN_UV.png
UV guide for body-texture painting. It is not a game texture.

livery_thumbnail.png
Local thumbnail used by My Liveries, previews, and packages.

ext_banner_c.png
Optional separate windshield or series-banner color texture.

{plate_filename}
Optional rear numberplate texture for supported road cars. Edit it and use
Update in Game to apply the change.

Material map files
------------------
EXT_Skin_D.png
Detail/material mask copied from the source skin. A black map is the safest
neutral starting point when inherited source zones are not wanted.

EXT_Skin_M.png
Metalness or material-control map where supported.

EXT_Skin_R.png
Roughness or reflection-control map where supported.

EXT_Skin_CC.png
Clearcoat-control map where supported.

EXT_Skin_CR.png
Clearcoat-roughness map where supported.

For grayscale control maps, brighter areas generally apply more of the effect
and darker areas apply less.

Project metadata
----------------
preview_project.json
Metadata for 3D Livery Preview and the project workspace. Do not edit it
manually unless you are intentionally repairing the project.

Typical workflow
----------------
1. Edit the artwork in your image editor.
2. Export the changed PNGs back into this folder.
3. Inspect the result in 3D Livery Preview.
4. Use Activate in Game or Update in Game from My Liveries.
"""


def official_project_readme() -> str:
    return """LiveryLab Official External Livery Project
================================================

This folder is the editable source of truth for one Official workflow livery.
Keep the PNG textures directly in this project folder. The Live 3D Preview
reads these files and reloads saved changes, making this folder the working link
between an external image editor and LiveryLab.

Workflow:
- A complete AC EVO content extract is not required.
- Activate in Game writes to Saved Games/ACE/ExternalLiveries.
- Find the activated car in AC EVO under Vehicles -> My Cars, not Vehicle Hub.
- AC EVO currently does not display the custom LiveryLab livery name in game.
- The livery can work in Multiplayer when the other participants who need to
  see it have the same livery installed.

Main texture files:
- EXT_Skin_C.png: main visible body color texture.
- EXT_Skin_D.png: detail/material mask.
- EXT_Skin_R.png: roughness control.
- EXT_Skin_M.png: metalness control.
- EXT_Skin_CC.png: clearcoat control.
- EXT_Skin_CR.png: clearcoat roughness control.
- EXT_Banner_C.png: optional separate banner color texture.

For grayscale control maps, brighter areas generally apply more of the effect
and darker areas apply less. Available maps vary by car.

Project support files:
- external_livery.json: Official material-channel data used during activation.
- official_external_project.json: LiveryLab project identity and source data.
- preview_project.json: Live 3D Preview configuration.
- livery_thumbnail.png: local My Liveries and package thumbnail.
- SavedCar: required local SavedCar data for the selected vehicle variant.

Do not edit JSON files or SavedCar data manually unless you are intentionally
repairing the project. Do not move the PNGs into a separate textures folder.

Typical workflow:
1. Open this project folder from My Liveries.
2. Edit the PNG textures with your preferred image editor.
3. Keep Live 3D Preview open to inspect saved changes.
4. Use Activate in Game or Update in Game from My Liveries.
5. Start AC EVO and select the car under Vehicles -> My Cars.
""".replace("\r\n", "\n").strip() + "\n"


# Exact SHA-256 hashes of historical LiveryLab-generated root README contents.
# Custom README files are preserved unless they carry the managed marker or
# match one of these known generated versions.
LEGACY_MANAGED_README_HASHES = {
    "00ee029103b0d6741279244f6c57b93f9bad2b3229ce45f5cdc4b00cdde54e88",
    "151eee22a810f8ddb1f1b7e306f839471136b24d25f4b03542be9551ee08a094",
    "3dbb517b0b59fa051980bc548ac4b1292bd90b4c352cd1d7185415d97d27ffa4",
    "44a08770573c53396d96a4a73167886cbcc9012a3c2e6a9ecda462f5be9c93f2",
    "4a673079acd0aae0b8a0aa2c84aeb82bff7e9fa0b22a9948cc354a94ef4f2e6b",
    "62840473a7dc29854c162072c4b8e22d6aa528c394790750da756b9e8d15a0f1",
    "929e00ef1002ff2c2c6a4c43643a9a78e6bbb9bfffeb407a6ff5448eafeb9d95",
    "aec787fe14fbf3ec7d0be7f59078c2e46b5b7584fde6f9dd65e7ec5faff3b094",
    "adfe1f73093b75382b39045ce384c11d023b41359e4690943648a918a5efd35f",
    "cead752af0a82b25b170da8a75a30b366822bf9a45e95ea0aeab73ebe4125516",
    "d551f38d5fabd70726231fe4befeecf447afc06d48192e36b44df10a7e955221",
    "d5aef010ad4330cfe922362026aac71b2f56aac951d523ce4412b64afb1be9d4",
    "d5e70675234e2fab858bf59b1308c94a15a8628978ada30fd2576065af5895ce",
    "d9c1fa780988da64931a4e289c3f5894ece19ac4587746368e564404cc4061ed",
    "f13b015ee877fd20c7d9e3cb88597780b2ff3bfdf27900c11d166e589e617024",
}


def normalized(text: str) -> str:
    return str(text or "").replace("\r\n", "\n").strip()


def is_managed_root_readme(text: str) -> bool:
    clean = normalized(text)
    if not clean:
        return True
    if MANAGED_MARKER in clean:
        return True
    digest = hashlib.sha256(clean.encode("utf-8")).hexdigest()
    return digest in LEGACY_MANAGED_README_HASHES


def is_managed_advanced_project_readme(text: str) -> bool:
    clean = normalized(text)
    return clean.startswith("LiveryLab Skin Project\n") or clean.startswith("LiveryLab Advanced Skin Project\n")


def is_managed_official_project_readme(text: str) -> bool:
    return normalized(text).startswith("LiveryLab Official External Livery Project\n")


def is_managed_driver_project_readme(text: str) -> bool:
    clean = normalized(text)
    return clean.startswith("LiveryLab driver project\n") or clean.startswith("LiveryLab Advanced driver project\n")
